New to java

G

Glen Davie

Can someone explain what I have done wrong and how can it be corrected?

MyQueue.java:37: warning: [unchecked] unchecked call to add(E) as a member
of the raw type java.util.ArrayList
list.add(tmp);
^

public class MyQueue
{
private ArrayList list;
public MyQueue()
{
list = new ArrayList();
}

public static void main(String[] args) { }

public <T> void add(T tmp)
{
list.add(tmp);
}

public void print()
{
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
}
}
 
D

ddaglas

Glen,

If you're looking to eliminate the warning, then specify <Object> as
your container type:

public class MyQueue {
private ArrayList<Object> list;
public MyQueue() { list = new ArrayList<Object>();
public static void main(String[] args) { }
public void add(Object tmp) {
list.add(tmp);
}
public void print() {
for (int i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
}
}

However, to make best use of Java 1.5 generics, tie it together with a
unified parameter type (T):

public class MyQueue<T> {
private ArrayList<T> list;
public MyQueue() {
list = new ArrayList<T>();
}
public static void main(String[] args) { }
public void add(T tmp) {
list.add(tmp);
}
public void print() {
for (int i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
}
}

To use:
MyQueue<String> queue = new MyQueue<String>();
queue.add("Hello there.");

--Dan
 
O

Oliver Wong

Glen,

If you're looking to eliminate the warning, then specify <Object> as
your container type:

public class MyQueue {
private ArrayList<Object> list;
public MyQueue() { list = new ArrayList<Object>();
public static void main(String[] args) { }
public void add(Object tmp) {
list.add(tmp);
}
public void print() {
for (int i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
}
}

I recommend that you do NOT just add <Object>, and instead simply ignore
the warning (though the best solution would be to spend a day or two
studying Java generics to understand the what the warning really means). If
you don't specify a container type, that's basically saying "I don't know
what container type I should use yet", which is fine, and is honest. If you
specify <Object>, you're saying "I know what the container type should be;
it should be Object", and so you might end up with incorrect code.

- Oliver
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top