This question already has answers here:
What do < and > mean such as implements Comparable<BigInteger>?
(2 answers)
Closed 9 years ago.
So I see people putting <> after declaring a collection. I know that it is used to specify which data type the collection contains. I haven't seen it used in any other cases so I was just wondering what it is called and if their are any other ways of using this technique? Thanks
Angled brackets/Generics are used for defining the data type that can be stored in the collection. Without generics, you can store entities of type Object, which means anything as all the classes extend from Object. But in business scenario we may not need such a generic collection and would like to avoid putting different kind of objects in a collection. For example if you have a collection of names, you may not want numbers to be stored in such a collection. To restrict this you can define collection with , this will mandate the coder to store only the String type values in the collection.
Java Generics. You call the thing inside the angled brackets a type parameter.
From Java Tutorials: JDK 5.0 introduces several new extensions to the Java programming language. One of these is the introduction of generics.
See http://docs.oracle.com/javase/tutorial/extra/generics/intro.html
Related
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 8 months ago.
I saw some code in Java that used code similar to
Collection<Cars> carsCollection = new ArrayList<>(); But I am a bit confused about the word Collection.
I have a basic understanding of Collections in general, and how a list or queue is part of the collections but I am having a hard time understanding why they would use Collection<Cars> instead of ArrayList<Cars>. All the information I find on the internet about Collections is how lists and queues use them but I haven't seen much other code that uses the Collections keyword itself, most of them just implement arrays or lists or something else that is a part of the Collections framework. How do you use it or why use it? I tried casting it to an ArrayList like ArrayList<Cars> aList = new ArrayList<>(carsCollection) and it said their was an issue with casting it to an ArrayList.
As people have mentioned Collection is an interface, an interface in Java is a tool for abstraction. So the way to think about it is in terms of generality, where a Collection in this case is the most general term. Then you have, for example List, Map or Set which in turn are more specific abstractions of the idea of a Collection, finally you have the implementations for example ArrayList, HashSet and HashMap.
Generally you want to be as abstract as possible, i.e. using the most general abstraction that still fullfills the requirements that you have on your code.
In your example with Collection<Car> and ArrayList<Car> (which probably ought to be List<Car>), my guess would be that in the case of Collection<Car> that the code doesn't care about the order, because that isn't a requirement of the Collection abstraction, but in the case of the List abstraction it is.
I'd recommend that you read the javadoc for Collection and the other interfaces and implementations.
It is just an interface for a collections alike structures Lists, Sets,Maps etc. It denotes fact that this is a "collection" of object and exposes some specific methods.
Doing this allows you to easily change the type of collection later. Maybe a LinkedHashSet yields better performance? This will be possible because your code is oblivious to the real type of collection and thus cannot call methods that aren’t available in all Collection types.
You might want to read up on the Collections Framework.
This question already has answers here:
How to create a generic array in Java?
(32 answers)
Closed 8 years ago.
I have a good understanding of data structures and can happily implement them in C++ without issue; I get a little tripped up in Java though due to the generic implementation constraints.
Specifically, I get confused when I'm trying to create a data structure backed by an array. I know, for example, that I cannot do this:
public class HashTable<T> {
private T[] table;
public HashTable() {
table = new T[10]; //Type param T cannot be instantiated directly.
}
}
I also know that if I back my generic array list with an object array, I'm going to have to suppress a number of "unchecked cast" warnings which seems of ill form.
What is the best way to create an array-based data structure in Java? Is there some trick that can be used to do it in a cleaner manner than just creating a straight object array and dealing with the messy casting?
Instead of using a raw array, use an ArrayList<T>. It's basically a generic wrapper around an array, with a bunch of additional features.
This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
Closed 9 years ago.
I have observed in Java programming language, we code like following:
List mylist = new ArrayList();
Why we should not use following instead of above one?
ArrayList mylist = new ArrayList();
While the second option is viable, the first is preferable in most cases. Typically you want to code to interfaces to make your code less coupled and more cohesive. This is a type of data abstraction, where the user of mylist (I would suggest myList), does not care of the actual implementation of it, only that it is a list.
We may want to change the underlying data structure at some point, and by keeping references, we only need to change the declaration.
The separation of Abstract Data Type and specific implementation is one the key aspects of object oriented programming.
See Interface Instansiation
Just to avoid tight coupling. You should in theory never tie yourself to implementation details, because they might change, opposite to interface contract, which is supposed to be stable. Also, it really simplifies testing.
You could view interface as an overall contract all implementing classes must obey. Instead, implementation-specific details may vary, like how data is represented internally, accessed, etc. - the information that you'd never want to rely on.
If you use ArrayList, you are saying it has to be an ArrayList, not any other kind of List, and to replace it you would have to change every reference to the type. If you use List you are making it clear there is nothing special about the List and it is used as a plain list. It can be changed to another List by changing just one line.
I saw sometimes a type object inside <> beside of another object type declaration.
For instance:
NavigableMap<Double, Integer> colorMap = new TreeMap<Double, Integer>()
or
private final CopyOnWriteArrayList<EventListener> ListenerRecords =
new CopyOnWriteArrayList<EventListener>();
Could you give me an easy explication?
They're known as generics in java, and templates in C++.
http://java.sun.com/developer/technicalArticles/J2SE/generics/
These are called Generics. Here http://java.sun.com/docs/books/tutorial/java/generics/index.html is a tut from sun for them.
As some others said before: Your dealing with Java Generics. They're in Java since SDK 1.5.
E.g:
new CopyOnWriteArrayList<EventListener>()
means that you're creating a new (concurrent) ArrayList which is able to store objects of type EventListener. If you would create an ArrayList the old (pre Java 1.5) way like:
new ArrayList()
All contained objects would be of type Object and you would have to cast them to their real type. See also http://en.wikipedia.org/wiki/Generics_in_Java#Motivation_for_generics.
These are called Generics in Java. They give you a way to tell the compiler what type the collection is going to hold.
http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
They're called Generics, and allow the compiler to do type checking of contents of lists etc, and also reduces the amount of casting you have to do in your code.
It's also helpful when reading code, as you know what type of object can be put into the item in question, or what type to expect out of it.
Java's implementation isn't as thorough as C++, as Java's is only available at compile time.
At runtime, the type information is no longer available.
In your example TreeMap the key of the TreeMap has type Double and the value referenced by this key has the type Integer. And as already answered it's called generics.
This is an extension introduced in java 1.5. This makes code more readable
They are Generics, classes that are written with one or more types left to be specified later, so they can be used with any type. The generics can be very useful for containers or algorithms, where the algorithm or the data structure used is independent from the actual type stored or manipulated.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why should the interface for a Java class be prefered?
I m relatively new to java and i have just started on collections framework.
While on ArrayList I encountered on two ways people declare it. For example to declare an ArrayList of Strings :
List<String> l = new ArrayList<String>();
or
ArrayList<String> al = new ArrayList<String>();
Which one of these two should I use and what is the difference between them?
I know that the actual methods called are decided at runtime and hence the methods called will all be of ArrayList class only but still the first declaration restricts the methods that can be called.
The first way is, I have heard, called "coding to an interface". Any method will be invoked using the variable l and hence only methods provided by List interface can be called, whereas, in the second example we can call all the methods provided not only by List but by the Object class also (like finalize(), wait() etc). So why even in the first place people even use the first declaration??
You should always use least specific interface possible. This makes it easier to substitute alternate implementations if a more appropriate one exists. For example, methods that take List don't care if the list is a linked list or an array list. You can choose whichever one is more appropriate.
I personally recommend using List<String> l = new ArrayList<String>();
The reason is you typically don't need to know you're working with an ArrayList. You just need something that operates like a list. There's a lot of behaviors on ArrayList that people don't need access to. Consider "EnsureCapacity". They don't need that - they just need the List operations. As a general rule, you want to limit the exposure of data and functionality on a "need to know" basis, and users of your list do not need to know (by default) what implementation you used.
Obviously, if they do need to know that you're using an ArrayList instead of a LinkedList, for instance, then you would want to use an ArrayList reference instead of a List reference. For most purposes though, that's not necessary.