Java public void list

1. List

List : is a raw type, therefore not typesafe . It will only generate a runtime error when the casting is bad. We want a compile time error when the cast is bad. Not recommended to use.

2. List

public static void test(List list) < System.out.println(list); // Works >
public static void test(List list) < list.add(new Long(2)); // Error list.add("2"); // Error System.out.println(list); >

3. List

public static void test(List list) < // T cannot be resolved System.out.println(list); >

Sometimes, I see , or , or , . Are they all the same or do they represent something different?
4. List

public static void test(List list)

10 Answers 10

2) You can think of that one as «read only» list, where you don’t care about the type of the items.Could e.g. be used by a method that is returning the length of the list.

3) T, E and U are the same, but people tend to use e.g. T for type, E for Element, V for value and K for key. The method that compiles says that it took an array of a certain type, and returns an array of the same type.

4) You can’t mix oranges and apples. You would be able to add an Object to your String list if you could pass a string list to a method that expects object lists. (And not all objects are strings)

@if_zero_equals_one Yes, but you would then get a compiler warning (it would warn and say that you are using raw types), and you never want to compile your code with warnings.

For the last part: Although String is a subset of Object, but List is not inherited from List.

Very good point; many assume that because class C inherits from class P, that List also inherits from List. As you pointed out this is not the case. The reason why was that if we could cast from List to List, then we could put Objects into that list, thus violating the original contract of List when attempting to retrieve an element.

The notation List means «a list of something (but I’m not saying what)». Since the code in test works for any kind of object in the list, this works as a formal method parameter.

Using a type parameter (like in your point 3), requires that the type parameter be declared. The Java syntax for that is to put in front of the function. This is exactly analogous to declaring formal parameter names to a method before using the names in the method body.

Regarding List not accepting a List , that makes sense because a String is not Object ; it is a subclass of Object . The fix is to declare public static void test(List set) . . But then the extends Object is redundant, because every class directly or indirectly extends Object .

I think «a list of something» is a better meaning for List since the list is of some specific but unknown type. List would really be «a list of anything» since it can indeed contain anything.

@ColinD — I meant «anything» in the sense of «any one thing». But you’re right; it means, «a list of something, but I’m not going to tell you what».

@ColinD it was he meant why did you repeat his words? yes it was written with a little different words, but the meaning is the same.

The reason you cannot cast List to List is that it would allow you to violate the constraints of the List .

Think about the following scenario: If I have a List , it is supposed to only contain objects of type String . (Which is a final class)

If I can cast that to a List , then that allows me to add Object to that list, thus violating the original contract of List .

Thus, in general, if class C inherits from class P , you cannot say that GenericType also inherits from GenericType .

N.B. I already commented on this in a previous answer but wanted to expand on it.

tyvm, I upload both your comment and your answer, since it is a very good explanation. Now where and why would people use List ?

Generally you should not use List as it sort of defeats the purpose of generics. However, there are cases where old code might have a List accepting different types, so you might want to retrofit the code to use type parameterization just to avoid compiler warnings for raw types. (But the functionality is unchanged)

I would advise reading Java puzzlers. It explains inheritance, generics, abstractions, and wildcards in declarations quite well. http://www.javapuzzlers.com/

Let us talk about them in the context of Java history ;

List means it can include any Object. List was in the release before Java 5.0; Java 5.0 introduced List, for backward compatibility.

List list=new ArrayList(); list.add(anyObject); 

? means unknown Object not any Object; the wildcard ? introduction is for solving the problem built by Generic Type; see wildcards; but this also causes another problem:

Collection c = new ArrayList(); c.add(new Object()); // Compile time error 

Means generic Declaration at the premise of none T or E type in your project Lib.

In your third point, «T» cannot be resolved because its not declared, usually when you declare a generic class you can use «T» as the name of the bound type parameter, many online examples including oracle’s tutorials use «T» as the name of the type parameter, say for example, you declare a class like:

you are saying that FooHandler’s operateOnFoo method expects a variable of type «T» which is declared on the class declaration itself, with this in mind, you can later add another method like

public void operateOnFoos(List foos) 

in all the cases either T, E or U there all identifiers of the type parameter, you can even have more than one type parameter which uses the syntax

in your forth ponint although efectively Sting is a sub type of Object, in generics classes there is no such relation, List is not a sub type of List they are two diferent types from the compiler point of view, this is best explained in this blog entry

String[] can be cast to Object[]

List cannot be cast to List .

For lists it is more subtle than that, because at compile time the type of a List parameter passed to a method is not checked. The method definition might as well say List — from the compiler’s point of view it is equivalent. This is why the OP’s example #2 gives runtime errors not compile errors.

If you handle a List parameter passed to a method carefully so you don’t force a type check on any element of the list, then you can have your method defined using List but in fact accept a List parameter from the calling code.

A. So this code will not give compile or runtime errors and will actually (and maybe surprisingly?) work:

public static void main(String[] args) < List argsList = new ArrayList(); argsList.addAll(Arrays.asList(args)); test(argsList); // The object passed here is a List > public static void test(List set) < Listparams = new ArrayList<>(); // This is a List params.addAll(set); // Each String in set can be added to List params.add(new Long(2)); // A Long can be added to List System.out.println(params); > 

B. This code will give a runtime error:

public static void main(String[] args) < List argsList = new ArrayList(); argsList.addAll(Arrays.asList(args)); test1(argsList); test2(argsList); > public static void test1(List set) < Listparams = set; // Surprise! Runtime error > public static void test2(List set) < set.add(new Long(2)); // Also a runtime error >

C. This code will give a runtime error ( java.lang.ArrayStoreException: java.util.Collections$UnmodifiableRandomAccessList Object[] ):

public static void main(String[] args) < test(args); >public static void test(Object[] set) < Object[] params = set; // This is OK even at runtime params[0] = new Long(2); // Surprise! Runtime error >

In B, the parameter set is not a typed List at compile time: the compiler sees it as List . There is a runtime error because at runtime, set becomes the actual object passed from main() , and that is a List . A List cannot be cast to List .

In C, the parameter set requires an Object[] . There is no compile error and no runtime error when it is called with a String[] object as the parameter. That’s because String[] casts to Object[] . But the actual object received by test() remains a String[] , it didn’t change. So the params object also becomes a String[] . And element 0 of a String[] cannot be assigned to a Long !

(Hopefully I have everything right here, if my reasoning is wrong I’m sure the community will tell me. UPDATED: I have updated the code in example A so that it actually compiles, while still showing the point made.)

Источник

Interface List

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2) , and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator , add , remove , equals , and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator , that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Unmodifiable Lists

  • They are unmodifiable. Elements cannot be added, removed, or replaced. Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown. However, if the contained elements are themselves mutable, this may cause the List’s contents to appear to change.
  • They disallow null elements. Attempts to create them with null elements result in NullPointerException .
  • They are serializable if all elements are serializable.
  • The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array.
  • The lists and their subList views implement the RandomAccess interface.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

This interface is a member of the Java Collections Framework.

Источник

Читайте также:  Import javascript into javascript
Оцените статью