所以我有一個看起來像這樣的文件:添加和刪除元素設置爲HashMap中的值
1st 2nd nth
e1, v1, 1
e1, v3, 2
e1, v4, 4
e1, v5, 7
e2, v1, 1
., ., .
., ., .
., ., .
,我想的第一列是一個HashMap的關鍵(E1或e2或者e3),並且這個值是一個名爲「Ratings」的ArrayList,我希望第二列在ArrayList的第n個索引內具有它的值(一個int)。
這裏是我的代碼在它的全部迄今:
import java.util.*;
import java.io.*;
public class Setup
{
public static void Setup(String[] args)
{
String user;
int value, location;
//Create a Hashmap that holds a string key and an ArrayList value
HashMap<String, ArrayList<Integer>> userRatings = new HashMap<String, ArrayList<Integer>>();
try
{
BufferedReader bufferReader = new BufferedReader(new FileReader("Student list.txt")); //read from file
String line, sentence; //declare two string variables
String[] sData; //declare a string array (store the contents here)
line = bufferReader.readLine(); //Read the line
while (line != null) //While there is a line, do this:
{
line = bufferReader.readLine();
sData = line.split(", "); //Into the string array, enter individual values in the line split by the ", " characters
int iData[] = new int[sData.length]; //Create an int array the size of the string array
user = sData[0];
for (int i = 0; i <sData.length; i++) //fill the int array with the int-version of the string array
{
iData[i] = Integer.parseInt(sData[i]); //pass the strings as integers into the integer array
}
value = iData[1];
location = iData[2];
if(!userRatings.containsKey(user)) //The user does not have ratings.
{
ArrayList<Integer> ratings = new ArrayList<Integer>();
// ratings = userRatings.get(user);
for (int j = 0; j < 50; j++)
{
ratings.add(j);
}
System.out.println(user + " " + userRatings.get(user));
}
else //The user has ratings
{
userRatings.get(user).add(location,value);
System.out.println(user + " " + userRatings.get(user));
}
}
bufferReader.close();
} catch (FileNotFoundException e)
{
System.out.println("File does not exist or could not be found.");
}
catch (IOException e)
{
System.out.println("Can't read from file");
}
catch (NullPointerException e)
{
}
}
}
我有修改的ArrayList內容的問題。
綜上所述: 在文件的第1列的每個字符串必須是在HashMap中(用戶列表) 程序會檢查是否有鑰匙,如果沒有鍵存在,它會創建一個新的自己的鑰匙arraylist作爲密鑰的值。 arrayList將填充50個索引,其中將包含「0」。 之後,ArrayList將從文件中添加新值,其中第二列中的整數將被添加到第n列的對應值。
我該如何填充arraylist,以及如何編輯它,以便如果我想在用戶e6的第n個索引處添加新的整數,我可以?
謝謝@mprabhat!這很棒!很簡單,我沒有這樣想過,但這很有道理!拿出來,編輯它,然後放回去。 如果我要比較兩個不同的鍵的值,我將如何處理? 即我想比較e1的陣列列表和e2的陣列列表。 –
如果你想比較兩個ArrayList,那麼你將不得不循環檢查並逐一比較內容。 – mprabhat
另一種方法是將兩個ArrayList轉換爲Array,然後調用[Arrays.equals](http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html) – mprabhat