Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

collections doubt

 
rajesh baba
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
class animal
{
animal()
{
System.out.println("i am called");
}
}
class alist
{
public static void main(String[] args)
{
ArrayList a1=new ArrayList();
System.out.println("intial size of array"+a1.size());
a1.add("1");
a1.add("2");
a1.add(new String("String"));
for(int i=0;i<9;i++)
a1.add(new animal());
animal a=(animal)a1.get(3);
System.out.println(a1);
Object[] list=a1.toArray();
Object sum=0;
for(Object k:list)
System.out.println("object is"+k);
}
}
output:
C:\jdk1.5.0_11\bin\coll>javac alist.java
Note: alist.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

what the note mean by i don't understand can any body explain
 
Louis Moloney
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Collections in java 1.5 are type safe.

you are using stuff like this:
List list = new List();

which anything can be put in

now you can do stuff like List<String> list = new ArrayList<String>();
which will allow you to add Strings and only strings.

the warnings you are getting is java telling you that you are using the
old way which is not type safe.
 
Vivian Josh
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by rajesh baba:
import java.util.*;
class animal
{
animal()
{
System.out.println("i am called");
}
}
class alist
{
// remaining code
}
output:
C:\jdk1.5.0_11\bin\coll>javac alist.java
Note: alist.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

what the note mean by i don't understand can any body explain




The 'Note' is warning and telling you that this class uses unsafe operations.

Java 1.5 has implemented Type safe collections. With this you can specify what kind of data would be collected in List. Eg: You can declare ArrayList to store all String data.

List<String> mylist = new ArrayList<String>();

You can add String objects only to this list. If you try to insert other datatype then compiler will throw error.

Here in your example, the class is using old list type, which is not type safe. So you can add any object to that list. As you are compiling this with java 1.5 its warning you that collection is not typesafe.

Second note is telling you that , recompile this class with -Xlint:unchecked for details.

If you recompile with that it will show you where exactly you are trying to add wrong data. But in your case it will not show that b'coz you are not using typesafe collection .

Hope this helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic