-1

I was messing around with lists and got to this code (its a part of the main):

List l1 = new ArrayList<Object>();
List l2 = new ArrayList<String>();
Object t = "a";
l1.add("a");
l2.add(t);
System.out.println(l1.equals(l2));
System.out.println(l2.get(0));

The dynamic type of l2 is ArrayList(type:String) , but I managed to add an Object to it. Moreover, it said the lists are equal. I thought that maybe it casts it to String somehow, but then I tried:

Object t = 9;

And it still worked. Pretty sure it has something to do with the list being a raw type, but still, I can't understand how I can add an object to an ArrayList(type: String). Thanks in advance.

Bar
  • 196
  • 10

3 Answers3

3

You are declare l2 as raw list. Thus you can add element of any type.

Regarding the equality of the l2 and l1 lists the documentation of equals method on the arraylist class says:

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal

.

Mikhail Chibel
  • 1,865
  • 1
  • 22
  • 34
  • Are l1 and l2 exactly the same, despite the fact one is implemented as an ArrayList and the other as an ArrayList? By "excatly the same" I mean I can add any type of element to both. Regarding the equality - I was not sure that "a" as an Object equals "a" as a String. I remembered Object's equals returns true iff the reference points to the same element, and when the types are different, it didn't seem likely. – Bar Jul 02 '16 at 10:46
  • @Bar As the quote from this answer already says, it doesn't matter how you declare these lists, if they contain _equal_ elements, then they are equal. `"a"` is a String, it doesn't matter if you assign it to an `Object` type variable. And please re-check what **polymorphism** is. – Tom Jul 02 '16 at 10:50
-1

The String class is a child of the Object class, so there is an inheritance of objects.

You should not use "equals" with inheritance.

More here : Why should I not use equals with inheritance?

Community
  • 1
  • 1
Simone C.
  • 369
  • 4
  • 14
-1

The thing is, the object could be converted back to string, either through an explicit conversion (in this case I'd call it unboxing, like in C#), or by the Java analog of C#'s ToString() method. Either way, the object could successfully be converted to a string so the runtime doesn't complain.

If t was a number converted to an object, either you'd get an exception or you'd get a string representation of that number.

List equality must have been overridden to call the .equals method of the objects in each list.

Paul Stelian
  • 1,381
  • 9
  • 27