J
johnmmcparland
Hi all,
If I have a collection and wish to clone it, do I always need to
suppress the unchecked cast warning in Java 5? E.g.
import java.util.ArrayList;
public class Test
{
private ArrayList<String> names = new ArrayList<String>();
public void addName(String name)
{
names.add(name);
}
public String toString()
{
String s = "";
for (String name : names)
{
s += name + " ";
}
return s;
}
@SuppressWarnings("unchecked")
public Object clone()
{
Test other = new Test();
// Warning Type safety: Unchecked cast from Object to
ArrayList<String>
other.names = (ArrayList<String>)this.names.clone();
return other;
}
public static void main(String args[])
{
Test test1 = new Test();
test1.addName("John");
Test test2 = (Test)test1.clone();
// Check they're the same
System.out.print("Test1: ");
if (test1.toString().equals(test2.toString()))
{
System.out.println("Equal - good");
}
else
{
System.out.println("Unequal - bad");
}
// Check they're not shallow copied
test1.addName("Bob");
System.out.print("Test2: ");
if (test1.toString().equals(test2.toString()))
{
System.out.println("Equal - bad");
}
else
{
System.out.println("Unequal - good");
}
}
}
Look at the clone() method - I've indicated what line raises the
warning and temporarily suppressed it.
If I have a collection and wish to clone it, do I always need to
suppress the unchecked cast warning in Java 5? E.g.
import java.util.ArrayList;
public class Test
{
private ArrayList<String> names = new ArrayList<String>();
public void addName(String name)
{
names.add(name);
}
public String toString()
{
String s = "";
for (String name : names)
{
s += name + " ";
}
return s;
}
@SuppressWarnings("unchecked")
public Object clone()
{
Test other = new Test();
// Warning Type safety: Unchecked cast from Object to
ArrayList<String>
other.names = (ArrayList<String>)this.names.clone();
return other;
}
public static void main(String args[])
{
Test test1 = new Test();
test1.addName("John");
Test test2 = (Test)test1.clone();
// Check they're the same
System.out.print("Test1: ");
if (test1.toString().equals(test2.toString()))
{
System.out.println("Equal - good");
}
else
{
System.out.println("Unequal - bad");
}
// Check they're not shallow copied
test1.addName("Bob");
System.out.print("Test2: ");
if (test1.toString().equals(test2.toString()))
{
System.out.println("Equal - bad");
}
else
{
System.out.println("Unequal - good");
}
}
}
Look at the clone() method - I've indicated what line raises the
warning and temporarily suppressed it.