I have the following piece of code:
public class Coordinate<T>{
T coordinate;
//rest of class
}
and then i later try to create an ArrayList which contains various Coordinates like so:
ArrayList<Coordinate> location = new ArrayList<Coordinate>();
and finally i add some coordinates to the location
location.add(new Coordinate(0));
location.add(new Coordinate("A"));
location.add(new Coordinate(0.1f));
these location.add() calls gives me the following warning:
Unchecked call to 'Coordinate(T)' as a member of raw type 'Coordinate'
I have searched for this warning and found some hits, but i was not able to figure out from those answers how i could make my application work, because i would like the ArrayList location to be able to hold different types of Coordinates, so i cant do something like
ArrayList<Coordinate<Integer>> location = new ArrayList<Coordinate<Integer>>();
.
Perhaps I'm just going about the problem in the wrong way?
Thanks in advance.
If you want to mix just numbers the following can be used ( <>
is the diamond from Java 7 and onwards, for earlier versions there is no type inference).
List<Coordinate<? extends Number>> location = new ArrayList<>();
location.add(new Coordinate<>(1));
location.add(new Coordinate<>(1.0));
If you want to use all sorts of Objects the following can be used:
List<Coordinate<?>> location = new ArrayList<>();
location.add(new Coordinate<>(1));
location.add(new Coordinate<>("Hello"));
Since you created the Coordinate
object without the generic parameter you got the warning.
new Coordinate(0) -> Unchecked call to 'Coordinate(T)' as a member of raw type 'Coordinate'
By changing the creation of Coordinate
to new Coordinate<>(1)
or whatever type is needed you avoid that problem.
In you array list you are putting Number
as well as String
.
ie you are adding objects in your array list, so its type should be Object
Because it is parent
of all the classes in java.
List<Coordinate<Object>> location = new ArrayList<Coordinate<Object>>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.