以下は、汎用Queueクラスのコードを表しています。今、私が主にやろうとしたことで、Queueクラスを使ってInteger配列の配列を作成しようとしました。しかし、Integer配列の配列内の要素をキューに適切に追加することができなかったため、私は試みても悲惨に失敗しました。 はここにいくつかの説明とコードです:Java:汎用クラスを使用して整数配列の配列を作成する
メイン:
import java.util.Iterator;
public class Main
{public static void main(String[] args)
{Queue <Integer[][]> Q= new Queue<Integer[][]>(); // creating the queue
Integer []i1={1,2,3};
Integer []i2={1,2,3};
Integer [][]i=new Integer[][]{i1,i2}; // creating the array of integer arrays
Q.add(i);
for(Iterator<Integer[][]> it=Q.iterator(); it.hasNext();){ System.out.print(it.next()+" "); }
System.out.println();
Iterator<Integer[][]> it=Q.iterator();
it.next();
it.remove();
System.out.println(Q);
}
}
そして、ここでは、キューのクラスである:だから
import java.util.*;
public class Queue <T>
{LinkedList<T>queue=new LinkedList<T>();
public void add(T x){ queue.add(x); NOF++; } // the regular add function
public void add(T[][] x) // the add function in case we get an array of Integer arrays
{ int i=0,j=0,k=0; T [] v;
while(x[i][j]!=null) // checking if the are still availabe arrays
{ v=x[i][j]; //1 passing to v an array (or at least what I thought I'd pass)
//but i don't think it works
while(v[k]!=null) // while the arrays has elements, add them to the queue
{ queue.add(v);
j++;
NOF++;
k++; }
j++; } }
public void remove(T x){ queue.remove(); }
public T peek(T x){ return queue.peek(); }
public String toString(){ String S=""; for(T x: queue)S=S + x + " "; return S; }
static int NOF=0;
public class QueueIterator<T> implements Iterator<T>
{ int index=0;
public boolean hasNext(){ return index < queue.size(); }
public T next(){ return (T) queue.get(index++); }
public void remove(){ if(index>0)queue.remove(index-1); } }
public Iterator<T> iterator(){ return new QueueIterator<T>(); }
}
それは明らかに動作しませんが、私は理解していませんなぜ、// 1でエラーが出るのですか?
Type mismatch, cannot convert from T to T[]
しかし、x [i] [j]は、 T []と同様に編集された。
アイデア、homies?
ヒント:変数名を長さ1に減らす必要はありません。しかし、これをしない理由は非常に多いです。つまり、あなたのクラスを行数で「短く」する誤った努力では、「普通の」Javaの人にとっては読みにくいものを作成します。あなたが知っている、Javaコーディングスタイルガイドがあり、あなたはそれらを全面的に違反しています。 – GhostCat
@GhostCat私はよくそれを行うことが知られていました;) –
これとは反対に、 'v'は' T [] '2行前に宣言されていますが、' x [i] [j] 'は' Tあなたが期待しているとおりです。 –