返回列表和整数的 Java 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6645177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java method returning List and a integer
提问by user549432
I have a method which reads a file and returns the contents of the text file in a list of String
array. Find the implementation of the method and how I read it below. Now I want to have the number of lines in the file as well. I can get it as shown below in the comment - Can you please let me know how can I pass the integer variable as well from the method and read the integer as well?
我有一个方法可以读取文件并在String
数组列表中返回文本文件的内容。在下面找到该方法的实现以及我如何阅读它。现在我也想要文件中的行数。我可以得到它,如下面的评论所示 - 你能告诉我如何从方法中传递整数变量并读取整数吗?
Below - i.e read file should return List
consisting of string arrays and an int as well.
下面 - 即读取文件应该返回List
由字符串数组和 int 组成。
public List<String[]> readFile() {
final List<String[]> userList = new ArrayList<String[]>();
BufferedReader bufferedreader = null;
try {
final String FileName="abs.txt"
bufferedreader = new BufferedReader(new FileReader(FileName));
String line = null;
while ((line = bufferedreader.readLine()) != null) {
// Add Variable ++ to get number of lines
final String[] values = line.split(",");
userList.add(values);
}
}
catch (FileNotFoundException ex) {
logError(ex.getMessage());
}
catch (IOException ex) {
logError(ex.getMessage());
}
finally {
try {
if (bufferedreader != null){
bufferedreader.close();
}
}
catch (IOException ex) {
logError(ex.getMessage());
}
}
return userList;
}
This is how I read it:
我是这样读的:
List<String[]> usersArray1 = new ArrayList<String[]>();
usersArray1=complianceTracker.readFile();
回答by Mark Elliot
In this instance, the number of lines in your file corresponds to the number of entries in usersArray1
, you can get this as usersArray1.size()
.
在这种情况下,文件中的行数对应于 中的条目数usersArray1
,您可以将其作为usersArray1.size()
.
回答by Mark Elliot
Um, you can't. Java can only return 1 object.
嗯,你不能。Java 只能返回 1 个对象。
You could make an encapsulating object to hold both the list and the int, or you can make the list you're using untyped and add in the int at the beginning or end, or just take the string value of the int and add it at the beginning or end and parse it later.
您可以创建一个封装对象来保存列表和 int,或者您可以使您使用的列表无类型并在开头或结尾添加 int,或者只获取 int 的字符串值并将其添加到开始或结束,稍后再解析。
Edit: You know what? You're trying to get the int that holds the length of the list. You don't have to do this: lists already know how big they are, and you can retrieve it with size()
.
编辑:你知道吗?您正在尝试获取包含列表长度的 int。您不必这样做:列表已经知道它们有多大,您可以使用size()
.
回答by Ted Hopp
You can't return a list of String that also contains an integer. There are several things that can be done to work around this:
您不能返回也包含整数的字符串列表。有几件事可以解决这个问题:
- Redefine your method to take a
List<String>
argument; the method fills the list and returns an int. - In the calling code, just use the
size()
method ofList
to determine the number of entries after the method returns. - Define a class that contains an
int
andList<String>
field, and return that instead of just theList<String>
. - Pass an
int[]
array as an argument initialized to a single element. Store the integer return value in position 0 of the array. (Requires that the array be at least 1 long when the method is called.)
- 重新定义你的方法来接受一个
List<String>
参数;该方法填充列表并返回一个整数。 - 在调用代码中,只需使用 的
size()
方法List
来确定方法返回后的条目数。 - 定义一个包含
int
andList<String>
字段的类,并返回该字段而不仅仅是List<String>
. - 将
int[]
数组作为初始化为单个元素的参数传递。将整数返回值存储在数组的位置 0。(要求调用方法时数组的长度至少为 1。)
There are probably other techniques people can come up with.
可能还有其他技术人们可以想出。
回答by Ajoy Bhatia
The simplest answer for this particular case is the one from Mark Elliott, who seems to be the only one who read what readFile()
is doing. The number of lines returned is usersArray1.size()
.
对于这种特殊情况,最简单的答案是 Mark Elliott 的答案,他似乎是唯一一个阅读readFile()
正在做的事情的人。返回的行数是usersArray1.size()
。
Another minor point. (Repeating your usage example here for reference)
另一个小点。(在此重复您的使用示例以供参考)
List<String[]> usersArray1 = new ArrayList<String[]>();
usersArray1=complianceTracker.readFile();
The first line is needlessly creating an instance of ArrayList<String[]>
which will be ready to be GC'ed after the second line executes. The usersArray1
reference will then refer to the object created on the first line of the readFile()
method, leaving no reference referring to the object created when usersArray1
was declared and initialized.
第一行不必要地创建了一个实例,ArrayList<String[]>
在第二行执行后,该实例将准备好进行 GC。然后usersArray1
引用将引用在readFile()
方法的第一行创建的对象,不留下引用usersArray1
声明和初始化时创建的对象的引用。
回答by Rudy
Create a bean.
创建一个豆。
public class ResultBean
{
private List<String> userArray;
private Integer anotherResult;
//create get set here
}
later your readFile only need to return this resultBean class.
稍后你的 readFile 只需要返回这个 resultBean 类。
public ResultBean readFile()
{
ResultBean bean = new ResultBean();
//your existing logic here.
bean.setUserArray(new ArrayList<String>()); //please implement your own set here. This is just an example.
bean.setAnotherResult(Integer.valueOf(0));
return bean;
}
回答by Satanfx55
ints are passed by value and not reference by default in java. An easy way around this is to create a small class. Try something like
在java中默认情况下int是按值传递而不是引用。解决这个问题的一个简单方法是创建一个小类。尝试类似
public class Data
{
public List<String[]> usersArray1;
public int value;
}
you could simply pass this to your method and store both the List of string[]s in there and the int could go in there too. Hope this helps!
您可以简单地将其传递给您的方法,并将 string[] 的 List 存储在那里,并且 int 也可以进入那里。希望这可以帮助!
回答by Ed Staub
Whenever you need to return more than one piece of data, you have two choices, sometimes used together:
每当您需要返回多条数据时,您有两种选择,有时会一起使用:
- Use (write, if necessary) a class wrapping the data to be returned (in this case, a List and an integer).
- Pass in as an argument that can hold some of the data, and can be modified by the method at hand.
- 使用(如有必要,写)一个包装要返回的数据的类(在本例中,是一个列表和一个整数)。
- 作为参数传入,可以保存一些数据,可以通过手头的方法进行修改。
回答by trutheality
There are basically two solutions to the problem of returning two things:
返回两个东西的问题基本上有两种解决方案:
- Create a class that keeps the two things together (makes a lot of sense if the integer and list of strings are passed around your code a lot).
- Use various tricks for returning one (or both) through the parameters, including:
- Passing a variable that is a
new int[1]
to the function, then changing the contents of that "array" in the function and reading from it after the function. - Passing in a class that encapsulates an integer in a mutable way (like an
AtomicInteger
). - Passing the
List
object to the function and modifying it (while maintaining the sameList
reference).
- Passing a variable that is a
- 创建一个将这两件事放在一起的类(如果整数和字符串列表在您的代码中传递了很多,这很有意义)。
- 使用各种技巧通过参数返回一个(或两个),包括:
- 将 a 变量传递
new int[1]
给函数,然后更改函数中该“数组”的内容并在函数之后读取它。 - 传入一个以可变方式封装整数的类(如
AtomicInteger
)。 - 将
List
对象传递给函数并修改它(同时保持相同的List
引用)。
- 将 a 变量传递