我是Java的初学者,我正在尝试使用类在Java中实现类似于数据结构的结构,并且我想在其中寻找匹配项……这个问题可能之前曾有人提出过,但我找不到它。请帮忙。代码如下:
public class operations extends DefFunctionHandler {
public Integer stream;
public Integer funct;
public String name;
public Integer funcgroup;
public Integer source;
}
//in another class
public void execute(String x) {
List<operations> oplist = new ArrayList<operations>();
operations op = new operations();
for(int i=0; i< functi.size();i++){
op.stream = str.get(i);
op.funct = functi.get(i);
op.funcgroup = functigroup.get(i);
op.name = nme.get(i);
op.source = src.get(i);
}
oplist.add(op);
Map<String, List<operations>> map = new HashMap<String, List<operations>>();
map.put(x, oplist);
List<operations> ope = map.get(x);
for (Map.Entry<String, List<operations>> entry : map.entrySet()) {
String key = entry.getKey();
List<operations> value = entry.getValue();
System.out.println(value);
}
}
如图所示,我有一个类
operations
,其中有多个字段。在另一种称为execute
的方法中,我将值以数组的形式添加到这些字段中。现在,我从用户那里得到name
的输入,我想在类/结构实现中搜索它,并将流的相应值返回给用户。我了解必须实现Map接口,但是我该怎么做呢?当我尝试打印value
时,得到otf.operations@3934f69a
Map Interface的实现和get方法正确吗?我糊涂了。请帮忙。编辑
execute
方法的代码现在看起来像这样 public void execute(String x) {
Map<String,Operations> obs = new HashMap<String,Operations>();
for(int i=0; i< functi.size();i++){
Operations op = new Operations();
op.stream = str.get(i);
op.funct = functi.get(i);
op.funcgroup = functigroup.get(i);
op.name = nme.get(i);
op.source = src.get(i);
obs.put(op.name, op);
}
System.out.println(obs.get(x));
}
最佳答案
您正在尝试打印列表:
System.out.println(value)
其中值是
List<operations>
。您要做的是打印该列表的值。然后执行以下操作:for (operations o : value) {
System.out.println(o.stream);
System.out.println(o.name);
}
编辑所需的代码:
public void execute(String x) {
ArrayList<operations> ops= new ArrayList<operations>();
for(int i=0; i< functi.size();i++) {
operations op = new operations();
op.stream = str.get(i);
op.funct = functi.get(i);
op.funcgroup = functigroup.get(i);
op.name = nme.get(i);
op.source = src.get(i);
ops.add(op);
}
Map<String,ArrayList<operations>> map = new HashMap<String, ArrayList<operations>>();
map.put(x, ops);
for (operations operation : map.get(x)) {
System.out.println(operation.name);
}
}
关于java - 使用 map 界面在类的实现的“结构”中查找值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17062242/