我需要从方法返回 2 种类型的值。
一个是Integer
,另一个是List
。
尝试使用
Map<String, Object> test = new HashMap<>();
// save the data
test.put("myList", list);
test.put("counter", 12);
// And read later like
Integer counter = test.get("counter");
List<someClass> myList = test.get("myList");
,但转换总是在 Eclipse/声纳中引发警告/错误。
因此,我尝试实现一个接口only以获得具有我需要的属性类型的对象。
private interface theList {
List<someCLass> myList;
Integer counter;
}
但我不认为这就是java中接口
的使用。我不想在任何类中实现方法或扩展此接口。
我需要的是有一种类型的元素,我可以在其中存储我需要的任何类型的信息并稍后读取它,就像我们在 javascript 中处理对象一样。
我只是不想为此创建另一个类或文件。
我可以使用什么结构?
I need to return from a method 2 types of values.
One is an Integer
and the other is a List<someClass>
.
Tried using
Map<String, Object> test = new HashMap<>();
// save the data
test.put("myList", list);
test.put("counter", 12);
// And read later like
Integer counter = test.get("counter");
List<someClass> myList = test.get("myList");
but the casts always fire warnings/errors in Eclipse/sonar.
So I tried to implement an interface only to have an object with the attributes type that I need.
private interface theList {
List<someCLass> myList;
Integer counter;
}
But I don't think this is the use of interfaces
in java. I don't want to implement methods or extend this interface in any class.
What I need is to have a type of element where I can store any type of information I need and read it later, just like we do with objects in javascript.
I just don't want to create another class or file for this.
What structure could I use?
发布评论
评论(1)
使用元组从方法返回多个值。元组只是一系列对象,它们不一定以任何方式相互关联。
简单实现的示例:
元组的良好实现是 配对 或 ImmutablePair 。
Spring元组可能有用 实现和文档。
Use
Tuples
for returning multiple values from the method. A tuple is just a sequence of objects that do not necessarily relate to each other in any way.Example of simple implementation:
The good implementation of tuples is Pair or ImmutablePair in Apache Commons Lang.
Probably can be useful Spring Tuples implementation and documentation.