英文:
Adding an object that has two separate Strings to an ArrayList in Java
问题
我已经做了一些谷歌搜索并阅读了我的文本,但似乎只能找到如何将单个字符串添加到ArrayList元素中,例如:arrayList.add("添加这个新字符串");
因为每个元素都是一个对象,我需要在每个元素中存储两个字符串。例如,我有一个包含以下内容的txt文件:
在Java中编程:ITC206
IT Helpdesk:ITC232
网络伦理:ITC311
当我读取文件并将其添加到ArrayList中时,它告诉我列表中有3个元素,每行一个,每行包含两个字符串。
当我尝试添加新行时,我似乎无法添加两个单独的字符串,一个用于课程名称,一个用于课程代码。
我已经尝试过手动添加,即arrayList.add("IT", "ITC000");
,但它会认为我试图指定元素,并告诉我无法将字符串("IT")转换为整数。
以下是我编写的代码。所有的代码都可以正常工作,直到我执行subjectList.add以将新行/元素添加到列表中。
public static void main(String[] args) {
// 创建数组列表
ArrayList<String> subjectList = new ArrayList<>();
Scanner input = new Scanner(System.in); // 导入扫描仪
// 从Subjects列表txt文件读取对象
try (BufferedReader list = new BufferedReader (new FileReader("ListofSubjects.txt"))) {
String listLine;
while ((listLine = list.readLine()) != null) {
subjectList.add(listLine);
}
} catch (IOException e) { // 捕获任何异常
}
// 获取新的学科名称和代码
System.out.println("输入您的新学科名称:");
String name = input.nextLine();
System.out.println("输入您的新学科代码:");
String code = input.nextLine();
// 使用Subject类中的两个字符串参数构造Subject
Subject newSubject = new Subject(name, code);
subjectList.add(newSubject);
// 我希望该元素包含名称和代码
//与列表的其他行一样,但是出现错误
System.out.println("列表大小? " + subjectList.size());
System.out.println("列表现在有: " + subjectList.toString());
}
也许我不需要单独添加它们,但是我需要能够单独检查学科名称和代码,因此我认为如果它们是元素中的单独字符串,这将更容易实现。
英文:
I have done some googling and read through my texts but I can only seem to find how to add a single string to an element of an arrayList i.e. arrayList.add("adding this new string");
as each element is an object, I need to store two strings in each element.
For example I have a txt file with the below already stored:
> Programming in Java: ITC206
> IT Helpdesk: ITC232
> Cyber Ethics: ITC311
When I read the file and add it to an ArrayList it tells me I have 3 elements in the list, one for each line, each line consisting of two strings.
When I try and add a new line in, I can't seem to add two separate strings, one for the course name and one for the course code.
I have tried this manually i.e. arrayList.add("IT", "ITC000");
but it assumes I am trying to specify the element and tells me I can't convert the string ("IT") to an int.
below is the code I have written. all works fine until I hit the subjectList.add to add the new line/element to the list.
public static void main(String[] args) {
// create array list
ArrayList<String> subjectList = new ArrayList<>();
Scanner input = new Scanner(System.in); // inport scanner
//read objects from List of Subjects txt file
try (BufferedReader list = new BufferedReader (new FileReader("ListofSubjects.txt"))) {
String listLine;
while ((listLine = list.readLine()) != null) {
subjectList.add(listLine);
}
} catch (IOException e) { // catch any exceptions
}
//get new subject name and code
System.out.println("Enter the name of your new Subject: ");
String name = input.nextLine();
System.out.println("Enter the code for your new Subject: ");
String code = input.nextLine();
//Subject constructor with two string arg from Subject class
Subject newSubject = new Subject(name, code);
subjectList.add(newSubject);
// I want the element to hold both the name and code
//like the other lines of the list but get error
System.out.println("List Size? " + subjectList.size());
System.out.println("the list now has: " + subjectList.toString());
}
Maybe I don't need to add these separately, however I need to be able to check the subject name, and the code separately, so figured this would be easier done if they are separate strings in the element.
答案1
得分: 0
你可以分别添加两个属性。
subjectList.add(newSubject.getName());
subjectList.add(newSubject.getCode());
或者如果你需要在一次调用中完成:
list.addAll(Arrays.asList(newSubject.getName(), newSubject.getCode()));
你也可以尝试仅为Subject对象创建一个List,但在需要改变方法以添加你的listLines时,需要改变你的方法。
List<Subject> subjectList = new ArrayList<>();
Scanner input = new Scanner(System.in); // 导入扫描器
// 从Subjects txt文件的列表中读取对象
try (BufferedReader list = new BufferedReader(new FileReader("ListofSubjects.txt"))) {
String listLine;
while ((listLine = list.readLine()) != null) {
Subject subject = new Subject();
subject.setName(listLine); // 或者setCode()
subjectList.add(subject);
}
} catch (IOException e) { // 捕获任何异常
}
英文:
You can add both attributes seperatly.
subjectList.add(newSubject.getName());
subjectList.add(newSubject.getCode());
Or if you need to do it in one call:
list.addAll(Arrays.asList(newSubject.getName(), newSubject.getCode()));
You could also try to create a List only for Subject objects, but when you need to change your approach to add your listLines.
List<Subject> subjectList = new ArrayList<>();
Scanner input = new Scanner(System.in); // inport scanner
//read objects from List of Subjects txt file
try (BufferedReader list = new BufferedReader (new FileReader("ListofSubjects.txt"))) {
String listLine;
while ((listLine = list.readLine()) != null) {
Subject subject = new Subject();
subject.setName(listLine); // or setCode()
subjectList.add(subject);
}
} catch (IOException e) { // catch any exceptions
}
答案2
得分: 0
问题在于您尝试混合您的列表包含的内容。
对于您从文件中读取的内容,您希望列表包含一个包含所有数据的单个 String
。
对于要添加的新主题,您希望添加一个自定义 Subject
类的对象。
您不能这样做*。您的列表要么是一个 List<String>
,要么是一个 List<Subject>
。
我的建议是使用更明确的类型(因为您已经有一个 Subject
类),并使用 List<Subject>
。首先,您必须更改 subjectList
的声明:
ArrayList<Subject> subjectList = new ArrayList<>();
这意味着您需要修改从文件中读取的代码,以便也构造 Subject
对象:
try (BufferedReader list = new BufferedReader(new FileReader("ListofSubjects.txt"))) {
String listLine;
while ((listLine = list.readLine()) != null) {
String[] lineParts = listLine.split(":", 2);
Subject subject = new Subject(lineParts[0].trim(), lineParts[1].trim());
subjectList.add(subject);
}
}
这样,在您的代码中稍后,您可以确保 subjectList
仅包含 Subject
对象,无论是从文件中读取还是后来添加的。
* 实际上在泛型出现之前,您是可以这样做的,但这是一个糟糕的想法,而且泛型等等是为了摆脱混合集合而引入的。
英文:
The issue is that you are trying to mix what your list contains.
For the stuff you read from the file you want the list to hold a single String
with all data.
For the new subject you want to add an object of your custom Subject
class.
You can't do that <sup>*</sup>. Your list is either a List<String>
or a List<Subject>
.
My suggestions is to have the more-explicit type (since you already have a Subject
class) and use List<Subject>
. First you must change the declaration of your subjectList
:
ArrayList<Subject> subjectList = new ArrayList<>();
That means you'll need to modify the code that reads from the file to construct Subject
objects as well:
try (BufferedReader list = new BufferedReader (new FileReader("ListofSubjects.txt"))) {
String listLine;
while ((listLine = list.readLine()) != null) {
String[] lineParts = listLine.split(":", 2);
Subject subject = new Subject(lineParts[0].trim(), lineParts[1].trim());
subjectList.add(subject);
}
}
This way later on in your code you can be sure that subjectList
contains Subject
objects only, no matter if you read them from the file or added them later.
<sup>* actually you can and before generics that was even somewhat common, but it's a terrible idea and among other things generics were introduced to get rid of inter-mixed collections.</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论