Solved Java Generics Question

Discussion in 'Plugin Development' started by xXMaTTHDXx, Aug 13, 2014.

Thread Status:
Not open for further replies.
  1. Offline


    Sorry if this isn't supposed to be here, I didn't know where else other developers would look, if it is in the wrong section please feel free to tell me, ill move it.

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

    myStrings.add(new Object());

    String anotherString = myStrings.get(0);

    I can add it to the arrayList because String is a type of object but I can't get a string because Object is not a type of string?
  2. Offline



    From what I know is that generics work like per reference/Type basis like if you do List<Bla> only objects with the reference of Bla are allowed, since you managed to get new Object() added is because that String implements Object but because it doesn't contain any logic data to be a String .get() fails.

    if you want to put custom objects use List<Object> but I would warn that it may be very dangerous using the combination of ArrayList and mixed objects, as it makes the chance lots easier getting duplicates.

    however I don't really know how to write my own generic class if thats what you wanted to know, but there alot of tutorials around there.
  3. Offline


    I just had a general question about generics, stuff like flexible methods and such, but no doubt the Oracle site has proved useful again. Time to research Wildcards! Thanks.
  4. Offline


    xXMaTTHDXx the use of Object and wildcard might be a hint that your general structure is 'bad'. Post the relevant code and we might be able to offer other (and perhaps better) suggestions.
  5. Offline


    That was my question but I read more on Oracle and found my answer, thanks though!
Thread Status:
Not open for further replies.

Share This Page