I read java doc about generic,But I didn’t understand it well. May you please explain about it?
You don’t say what you’re not understanding…
Generics accomplish at least two things: they make it (marginally) more convenient for the programmer to use a Collection and make it possible for the compiler to check for type-safe casts.
Prior to generics, the following would have compiled without issue, but failed at runtime with a ClassCastException:
void someMethod() {
ArrayList list = new ArrayList();
list.add( new Integer(100) );
expurgate( list );
}
// Removes 4-letter words from c. Elements must be strings
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (((String) i.next()).length() == 4)
i.remove();
}
The same code, updated to use Generics, now causes a compilation error, alerting the programmer to the problem:
void someMethod() {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add( new Integer(100) );
expurgate( list );
}
// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
for (Iterator<String> i = c.iterator(); i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}
C:\\GenericsExample2.java:4: expurgate(java.util.Collection<java.lang.String>) in GenericsExample2 cannot be applied to (java.util.ArrayList<java.lang.Integer>)
expurgate( list );
^
(Code borrowed from here)
I search about collection, But it is still unclear…
Collection dates = new ArrayList( ); dates.add( new Date( ) ); // unchecked, compile-time warning
I read about collection in JAVA learning book
I know ArrayList is a dynamic array, But I don’t understand what is collection.I read this in JAVA doc:
A Collection represents a group of objects known as its elements. The Collection interface is used to pass around collections of objects where maximum generality is desired. For example, by convention all general-purpose collection implementations have a constructor that takes a Collection argument. This constructor, known as a conversion constructor, initializes the new collection to contain all of the elements in the specified collection, whatever the given collection’s subinterface or implementation type. In other words, it allows you to convert the collection’s type.
It is unclear for me.
From head first JAVA
Although ArrayList is the one you’ll use most often,
there are others for special
TreeSet
Keeps the elements sorted and prevents duplicates.occasions. Some of the key .
HashMap
Let’s you store and access elements as namelvalue pairs.
linkedLlst
Designed togive better performance when you insert ordelete
elements from the middle ofthe collection. (In practice, an
ArrayUst isstill usually what you want.)
HashSet
Prevents duplicates inthe collection, and given an element, can
find that element in the collection qulcldy.
LinkedHashMap
Like aregular HashMap, except it can remember the order in
which elements (name/value pairs) were Inserted, orit can be
configured to remember the order In which elements were last
accessed.
Are these Linkedlist and treeset, The linked list and tree in data structure?
I cann’t understand What is the realtionship between collection, Arraylist, treeset.
Collection is an interface that is implemented by all the classes you’ve listed, notably ArrayList and TreeSet.
Because both ArrayList and TreeSet implement Collection, we can write a method that can print either an ArrayList or a TreeSet with no code changes and no need to detect what the incoming Object is. The fact that it implements Collection is enough to let us know that we can operate on it in a standard way.
import java.util.*;
public class CollectionsExample {
public static void main( String[] args ) {
new CollectionsExample();
}
public CollectionsExample() {
// because ArrayList implements Collection, I can declare a
// Collection, but store an Arraylist
Collection<String> list = new ArrayList<String>();
list.add( "array list - 1" );
list.add( "array list - 2" );
list.add( "array list - 3" );
printCollection( list );
// Because TreeSet implements Collection, it can be cast as
// one when need be, as below
TreeSet<String> set = new TreeSet<String>();
set.add( "tree set - 1" );
set.add( "tree set - 2" );
set.add( "tree set - 3" );
printCollection( (Collection<String>)set );
}
// if you actually read this code, put 'cafebabe' at the beginning of your next post
public void printCollection( Collection<String> collection ) {
for( Iterator<String> i = collection.iterator(); i.hasNext(); ) {
System.out.println( i.next() );
}
}
}
interface Shape {
public double area();
public double volume();
}
public class Point implements Shape {
static int x, y;
public Point() {
x = 0;
y = 0;
}
public double area() {
return 0;
}
public double volume() {
return 0;
}
public static void print() {
System.out.println("point: " + x + "," + y);
}
}
public class Main {
public static void main(String[] args) {
Shape p = new Point();
p.print();
}
}
I see an error in this line:
p.print();
Shape is an interface, either a collection.Then Why It doesn’t work for shape?
ArrayList<Integer> list = new ArrayList<Integer>();
As I understand, Generic is about using special type. In order to prevent bug.
Array list is a dynamic array that each of element of that can have any type of objects,But in this code, “<Integer>” makes Arraylist have only integer. Right?
public interface List<E> extends Collection<E> {
// Positional access
E get(int index);
E set(int index, E element); //optional
boolean add(E element); //optional
void add(int index, E element); //optional
E remove(int index); //optional
boolean addAll(int index,
Collection<? extends E> c); //optional
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// Range-view
List<E> subList(int from, int to);
}
What does it mean:
<E>
Please explain more about these lines:
E get(int index);
E set(int index, E element); //optional
public interface Collection<E> extends Iterable<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array operations
Object[] toArray();
<T> T[] toArray(T[] a);
}
May you explain more about these:
(Collection<? extends E> c)
(Collection<?> c)
I can’t understand anything from that code.confused!
Could you explain about List interface?
hmm I’ve never thought too much about these but here is my understanding.
E is the type parameter, so if you created your collection like this:
List<String> stringList = new ArrayList<String>();
then the “type parameter”, E, is the String class.
after that you can think of the methods changing from
boolean add(E element);
E get(int index);
E set(int index, E element);
to
boolean add(String element);
String get(int index);
String set(int index, String element);
So now when you use the variable you can only put Strings in there.
stringList.add("hello");
will be ok
but
stringList.add(new Integer(222));
will not compile.
A is another type parameter, not necessarily the same class as E.
and ? is another type parameter, which has to be the same class or a subclass of E.
All this and more is explained, in detail, on the Java Generics page, scroll to the bottom to find the bonus link for a tutorial on Generics.
Your example about Arraylist is understandable. But still I don’t understand that interface.
public interface List<E> extends Collection<E>
It is just an interface, How these types can do anything on it?
Just other class uses these interface for their methods.
May you give me more information about list?
Thanks in advance!
The <E> indicates that Generics are expected and will generate the unchecked warning if a type is not provided.
As to List, List is an extension of Collection, with List being a more specific Collection type.
(Every List is a Collection, but not every Collection is a List)
public class GenericMethodTest
{
// generic method printArray
public static < E > void printArray( E[] inputArray )
{
// Display array elements
for ( E element : inputArray ){
System.out.printf( "%s ", element );
}
System.out.println();
}
public static void main( String args[] )
{
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println( "Array integerArray contains:" );
printArray( integerArray ); // pass an Integer array
System.out.println( "\
Array doubleArray contains:" );
printArray( doubleArray ); // pass a Double array
System.out.println( "\
Array characterArray contains:" );
printArray( characterArray ); // pass a Character array
}
}
The generic cause more flexibility in this code,Not limitation of data type. Right?
publc interface Breakeable <T>{
public void dobreake(T t);
}
public class Glass implements Breakeable<String>{
public void dobreake(String message){
System.out.println(message);
}
}
If you don’t use generic here, This class works and only accept String. What is the usage of generic here?
public class Dish<U> implements Breakeable <U>{
public void dobreake(U u){
System.out.println(u.toString());
}
}
I guess that it must be this:
public class Dish<U> implements Breakeable <u>{
public void dobreake(U u){
System.out.println(u.toString());
}
}
Right? Because of “u”
Is this because of you?
I heard you the first time, your question still makes no sense.
The letter in the angle brackets is arbitrary. T is used convey the idea of Type and E is used for Element, U is something you put in and has exactly zero accepted meaning.
Now, on to the code, I have to admit, I’m lost. I have no idea what you’re trying to accomplish. I will say, though, that it looks like you’re trying to squeeze Generics in where they don’t need to be.
Just because you can, doesn’t mean you should.
To wit:
public class Dish implements Breakable {
public void doBreak( Object object ) {
System.out.println( object );
}
}
This code does everything your ‘generic’ code does, in a sensible, straightforward manner.
I know you’re just experimenting and these are contrived examples…but the purpose of generics, as far as I know, is to simplify working with Collections and add a degree of safety by allowing the compiler to make typesafe cast checks - do not start throwing them in every little piece of code simply because it will compile: have a reason to use them.
Back to your question, you’re asking if something occurs due to U, right?
What is the something?
Thank you very much.
In fact, I didn’t write that code myself, I read that code in book:
Sun Certified Programmer
for Java® Platform, SE6
1-May you give me an example that show how generic interface that you build yourself can be useful?
2-Please look at this code:
public class GenericMethodTest
{
// generic method printArray
public static < E > void printArray( E[] inputArray )
{
// Display array elements
for ( E element : inputArray ){
System.out.printf( "%s ", element );
}
System.out.println();
}
public static void main( String args[] )
{
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println( "Array integerArray contains:" );
printArray( integerArray ); // pass an Integer array
System.out.println( "\
Array doubleArray contains:" );
printArray( doubleArray ); // pass a Double array
System.out.println( "\
Array characterArray contains:" );
printArray( characterArray ); // pass a Character array
}
}
but the purpose of generics, as far as I know, is to simplify working with Collections and add a degree of safety by allowing the compiler to make typesafe cast checks
My question is:
How this code add a degree of safety by allowing the compiler to make typesafe ?
What is the advantage of List<?> vs List?
We can use any object in both case.
May you show me by an example What is the advantage of List<?> vs List?
public class WildCardTest {
public static void main(String[] args) {
ArrayList<?> i;
i=new ArrayList<Integer>();
// i=new ArrayList<Double>();
i.add(new Integer(726));
}
}
This code doesn’t compile,it has error about add method.
Please know me usage of wildcard by an example.
From Generics in the Java Programming Language Chapter 4, Paragraph 3
(First link of http://www.google.com/search?q=java+generics, honestly, do you not have google in your country?)
Collection<?> c = new ArrayList<String>();
c.add(new Object()); // compile time error
Since we don’t know what the element type of c stands for, we cannot add objects
to it. The add() method takes arguments of type E, the element type of the collection.
When the actual type parameter is ?, it stands for some unknown type. Any parameter
we pass to add would have to be a subtype of this unknown type. Since we don’t know
what type that is, we cannot pass anything in. The sole exception is null, which is a
member of every type.
On the other hand, given a List<?>, we can call get() and make use of the result.