How types were handled without generics in ArrayList prior to Java version 1.5

I have a question about the history of Java.
Java has ArrayListsince 1.2.
Java has been generic since version 1.5.

What was the ArrayListgeneric-free implementation for determining the type?

+4
source share
3 answers

Everything was done using Object(and many castings were involved), for example:

ArrayList list = new ArrayList();
list.add(new Thingy());
// ...
Thingy t = (Thingy)list.get(0);
// Note ---^^^^^^^^

The list only knew that it was saved Object, it was before the code, using the list to return back to the useful type.

, — , ClassCastException , , ; , , .. .. .. .

+7

generics ArrayList , Object, , , . .

, .

.

The following code snippet without generics requires casting:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);

:

    List<String> list = new ArrayList<String>();
    list.add("hello");
    String s = list.get(0);   // no cast
+3

stackoverflow.What, , somecode , . , , stackoverflow...

arraylist . , , .

ArrayList<String> list=new ArrayList<>();

generics,

ArrayList list =new ArrayList();

generics.If generics, . , .

for (Object o:list)
{
String s=(String)o;
System.out.println(s);
}

- this is what you need to do if you are not using generics. If you use generics

then

for(String s:list)
{
System.out.println(s)
}

Hope this helps .... :)

0
source

Source: https://habr.com/ru/post/1673285/


All Articles