I'll start by saying I am a Java (/programming) newbie and this is my first question on the website.
Just learnt how to make an ordered list in Java using recursive nodes. Everything was easy until I ran into this exercise asking me to write a method that would double whatever value is contained in each node. Here is the code I tried to write:
public class ListaInteri<E extends Integer>
{
private NodoLista inizio;
// Private inner class each instance of these has a raw type variable and a
// ref
// to next node in the list
private class NodoLista
{
E dato;
NodoLista pros;
}
// method that adds whatever is meant by x to the begging of the list
public void aggiungi(E x)
{
NodoLista nodo = new NodoLista();
nodo.dato = x;
if (inizio != null)
nodo.pros = inizio;
inizio = nodo;
}
// a method that switches last and first elements in the list
public void scambia()
{
E datoFine;
if (inizio != null && inizio.pros != null) {
E datoInizio = inizio.dato;
NodoLista nl = inizio;
while (nl.pros != null)
nl = nl.pros;
datoFine = nl.dato;
inizio.dato = datoFine;
nl.dato = datoInizio;
}
}
// and here is the problem
// this method is supposed to double the value of the raw type variable dato
// of each node
public void raddoppia()
{
if (inizio != null) {
NodoLista temp = inizio;
while (temp != null) {
temp.dato *= 2;
}
}
}
// Overriding toString from object (ignore this)
public String toString(String separatore)
{
String stringa = "";
if (inizio != null) {
stringa += inizio.dato.toString();
for (NodoLista nl = inizio.pros; nl != null; nl = nl.pros) {
stringa += separatore + nl.dato.toString();
}
}
return stringa;
}
public String toString()
{
return this.toString(" ");
}
}
and here is the error the compiler gives me.
ListaInteri.java:39: inconvertible types
found : int
required: E
temp.dato*=2;
^
1 error
Now keep in mind any kind of help would be greatly appreciated anyway here are the questions I would like an answer to.
- Why does this happen? Isn't there such a thing as type erasure of raw types during compile time where all info that has to do with parameters or arguments types is ignored?
- How do I fix this? The second method ( the one that switches first and last) shows it's actually ok for the compiler to change fields in nodes as long as it is passed by another raw type, while if we try to multiply it by 2 for example it's no longer ok because compiler now knows we are talking about an int/Integer so gives this error in return. Thanks in advance for any answers.
EDIT; sorry had to make it readable should be ok now. EDIT2: almost readable argh!