Declaring a LinkedList in Java

前端 未结 11 2088
北荒
北荒 2021-02-20 14:26

I always learn when we declare a collection we should do, Interface ob = new Class(), if i want to use for example a LinkedList i\'ll do List ob = new LinkedL

相关标签:
11条回答
  • 2021-02-20 14:41

    I won't always suggest you to use generics ..... Coz sometimes you may need to wrap different objects as here....

              String str="a string";
              boolean status=false;
    
              LinkedList ll = new LinkedList();
              ll.add(str);
              ll.add(status);
    

    In some situations like case of RMI, u can only send serialized data.....and suppose you want to send a class object(which is unserialized).......There you can wrap the members of the class(primitives) in a LinkedList and pass that object as a whole.......not worrying about the huge number of arguments...... Consider for eg:

           public Class DataHouse
           {
                 public int a;
                 public String str;
                 .
                 .
                 .
           }
    

    Now Somewhere u need to pass the objects.... You can do the following....

                 DataHouse dh =new DataHouse();
                 LinkedList ll = new LinkedList();
                 ll.add(dh.a);
                 ll.add(dh.str);
    
                 // Now the content is serialized and can pass it as a capsuled data......
    
    0 讨论(0)
  • 2021-02-20 14:53

    Nope.. This would be wrong, at the later stages if he wants to change his implementation from linked list to any other implementation of list type he will go wrong... So better to use the interface level declaration.

    0 讨论(0)
  • 2021-02-20 14:54

    Actually it would be better if it would be parametrized as both are raw types.

    0 讨论(0)
  • 2021-02-20 14:55

    the rule "always code to interfaces" must be taken with some flexibility. what you are suggesting is fine, and as you came to the conclusion, the only option.

    as a side note, coding to concrete classes like this is faster is most JVMs. deciding whether the performance is worth breaking the rule is the hard thing to decide.

    0 讨论(0)
  • 2021-02-20 14:55

    you can still have access to LinkedList methods by using List, all you have to do is to type cast for example

    ((LinkedList)ob).add()
    

    The point of using generic List and not LinkedList is because in case you simply change the type of lists you are using (let's say double linked list) your program will still work Generics are to simplify your code to be more portable and more "changeable"

    0 讨论(0)
提交回复
热议问题