Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, what does Enumeration<?> mean?

Tags:

java

What's does Enumeration<?> mean?

Is there any way to represent the general generic?

like image 638
user705414 Avatar asked Oct 15 '25 16:10

user705414


2 Answers

The <?> syntax is java's way to specifying that the generic type is "unbounded" - ie it can be "anything".

Enumeration<?> is an Enumeration with an "unbounded type" - you can assign an Enumeration of any type to such a variable, for example:

Vector<String> v = new Vector<String>();
Enumeration<String> es = v.elements();
Enumeration<?> e = es; // This assignment compiles OK

However, being unbounded, the nextElement() method of an Enumeration<?> with return type Object (even if it's actually an Enumeration<String>), so you'll have to cast if you want typed elements:

String s = (String)e.nextElement(); // Unsafe cast - compiler warning

For background, [Enumeration][1] is a typed interface with two methods [hasMoreElements()][2] and [nextElement()][3]. It was an early (poor) attempt that was superseded by [Iterable][4] and [Iterator][5]. A few old class use it, like [Vector][6] and [StringTokenizer][7].
like image 185
Bohemian Avatar answered Oct 18 '25 05:10

Bohemian


The question mark indicates that it stands for all types. Here's an example:

In addition to concrete instantiation there so-called wildcard instantiations . They do not have concrete types as type arguments, but so-called wildcards . A wildcard is a syntactic construct with a " ? " that denotes not just one type, but a family of types. In its simplest form a wildcard is just a question mark and stands for "all types".

Example (of a wildcard parameterized type):

public void printPair( Pair<?,?> pair) {   
System.out.println("("+pair.getFirst()+","+pair.getSecond()+")");
}

Pair<?,?> limit = new Pair<String,Long> ("maximum",1024L); 
printPair(limit);
like image 20
Chris Bunch Avatar answered Oct 18 '25 05:10

Chris Bunch