私はJava(/プログラミング)初心者であると言うことから始めます。これはWebサイトでの私の最初の質問です。
再帰ノードを使用してJavaで順序付きリストを作成する方法を学びました。この演習に出くわして、各ノードに含まれる値を2倍にするメソッドを作成するように求められるまで、すべてが簡単でした。これが私が書き込もうとしたコードです:
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(" ");
}
}
これがコンパイラが私に与えるエラーです。
ListaInteri.java:39: inconvertible types
found : int
required: E
temp.dato*=2;
^
1 error
とにかく、どんな種類の助けも大歓迎です。ここに私が答えたい質問があります。
- なぜこれが起こるのですか?コンパイル時のraw型の型消去のように、パラメーターや引数の型に関係するすべての情報が無視されるようなことはありませんか?
- これを修正するにはどうすればよいですか?2番目の方法(最初と最後を切り替える方法)は、別のraw型が渡される限り、コンパイラがノードのフィールドを変更しても実際には問題ないことを示していますが、たとえば2を掛けようとすると、問題はなくなります。コンパイラは、int / Integerについて話していることを認識しているため、このエラーが返されます。回答をよろしくお願いします。
編集; 申し訳ありませんが、読みやすくする必要がありました。EDIT2:ほぼ読みやすい引数!