gpt4 book ai didi

java - 如何防止在内部存储中存储重复的字符串

转载 作者:行者123 更新时间:2023-12-02 02:56:26 27 4
gpt4 key购买 nike

我尝试了两天但没有成功。我在 fragment 的 onStop 方法中将 arraylist 保存在内部存储中,然后在 onresume 方法中从内部存储中获取此数据。我正在检查字符串是否存在于内部存储的数组列表中,以防止在内部存储中存储重复的字符串,但这似乎不起作用。它每次都会在内部存储中存储重复的字符串。我不明白我在这里做错了什么。我将非常感谢您的帮助。

 public void saveTitleList (){
try {
FileOutputStream fileOutputStream= mContext.openFileOutput("radiotitle2.txt",MODE_PRIVATE);
DataOutputStream dataOutputStream=new DataOutputStream(fileOutputStream);
dataOutputStream.writeInt(stationName2.size());
ArrayList<String> titletest=getTitleList();
for(String line:stationName2){
if(!titletest.contains(line)){//here i am checking for duplicate strings in intenal file
dataOutputStream.writeUTF(line);
Log.d("title2 saved",line);
}

}
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<String> getTitleList(){
ArrayList<String> titleList= new ArrayList<>();
try {
FileInputStream fileInputStream= mContext.openFileInput("radiotitle2.txt");
DataInputStream dataInputStream= new DataInputStream(fileInputStream);
int size=dataInputStream.readInt();
for(int i =0;i<size;i++){
String line=dataInputStream.readUTF();
titleList.add(line);
Log.d("title2 from storage",line);
}
dataInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return titleList;
}

最佳答案

ArrayList 允许重复,而 HashSet 不允许重复。您应该使用 HashSet .

The important feature of Set interface is it does not allow the elements in duplicates; stores unique elements.

 HashSet <String> titleList= new HashSet <String>();

try {
FileInputStream fileInputStream= mContext.openFileInput("radiotitle2.txt");
DataInputStream dataInputStream= new DataInputStream(fileInputStream);
int size=dataInputStream.readInt();
for(int i =0;i<size;i++){
String line=dataInputStream.readUTF();
titleList.add(line);
Log.d("title2 from storage",line);
}
......

关于java - 如何防止在内部存储中存储重复的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42995279/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com