我正在研究一个大学项目,并且遇到了一个我无法弄清楚的问题。
我添加了一些byte [](字节数组到ArrayList,当我读回值时,所有值都是最后一个值的副本。
我需要这个ArrayList才能访问我的程序的其余部分。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Puzzles {
static ArrayList<byte[]> puzzleList = new ArrayList<byte[]>();
public static void getPuzzles() throws Exception
{
//Create 4096 128 zero bits followed by unique 16 bit random puzzle number.
ArrayList<byte[]> puzzles = Puzzles.createPuzzles();
//Array list to store the final completed puzzles.
ArrayList<byte[]> complete = new ArrayList<byte[]>();
byte[] puzzleKey;
DES a = new DES();
for(byte[] puzzle: puzzles)
{
byte[] fullPuzzle = new byte[26];
puzzleKey = a.generateRandomKey();
System.arraycopy(puzzle, 0, fullPuzzle, 0, puzzle.length);
System.arraycopy(puzzleKey, 0, fullPuzzle, fullPuzzle.length-puzzleKey.length, puzzleKey.length);
//System.out.println("puzzle="+ CryptoLib.getHexStringRepresentation(puzzle));
byte[] secretByte = createKey();
SecretKey secret = new SecretKeySpec(secretByte, 0, secretByte.length, "DES");
byte[] puzzleBytes = a.encrypt(fullPuzzle, secret);
// unencryptedPuzzleList.add(fullPuzzle);
complete.add(puzzleBytes);
}
FileInOut writer = new FileInOut();
writer.writeToBin(complete);
}
public static ArrayList<byte[]> createPuzzles()
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<4097; i++)
{
list.add(i);
}
Collections.shuffle(list);
byte[] messageNumber = new byte[18];
byte[] uniqueNumber = new byte[2];
for (int n=0; n<4096; n++)
{
uniqueNumber = CryptoLib.smallIntToByteArray(list.get(n));
System.arraycopy(uniqueNumber, 0, messageNumber, messageNumber.length-uniqueNumber.length, uniqueNumber.length);
System.out.println("messageno"+CryptoLib.getHexStringRepresentation(messageNumber));
puzzleList.add(messageNumber);----> **here is the problem.**
}
System.out.println("check="+ CryptoLib.getHexStringRepresentation(puzzleList.get(44)));
return puzzleList;
}
public static byte[] createKey()
{
Random r = new Random();
int key = r.nextInt(65536);
byte[] bkey = new byte[8];
byte[] messageKey = CryptoLib.smallIntToByteArray(key);
System.arraycopy(messageKey, 0, bkey, 0, messageKey.length);
return bkey;
}
}
我已经标记了ArrayList puzzleList,这是造成问题的原因。
我认为它与声明为静态的Arraylist有关。 Java不是我的强项,我可能犯了一个愚蠢的错误。
由于 保罗。