Java中是否有一些集合,可以在其中放置2个对象,然后通过在一个对象上调用一个方法以返回另一个对象? 例如:myColection [{o1},{o2}] myCollection.getNext(o1)重新调谐o2,反之亦然。
答案 0 :(得分:0)
Java中没有可用的集合可以直接解决此问题。我猜写自己的自定义逻辑将是解决方案。
我尝试了以下操作:
import java.util.*;
import java.lang.*;
import java.io.*;
class Node{
String data;
Node otherNode;
Node(String data){
this.data=data;
}
Node getOtherNode(){
return otherNode;
}
@Override
public String toString(){
return this.data;
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Node first = new Node("FIRST");
Node second = new Node("SECOND");
first.otherNode = second;
second.otherNode = first;
System.out.println(first.getOtherNode());
}
}
答案 1 :(得分:0)
如何使用地图?
public static <T> Map<T, T> alternate(T s1, T s2)
{
Map<T, T> map = new HashMap<>();
map.put(s1, s2);
map.put(s2, s1);
return map;
}
public static void main(String[] args)
{
Map<String, String> map = alternate("hello", "world");
System.out.println(map.get("hello"));
System.out.println(map.get("world"));
}
答案 2 :(得分:0)
如果要循环收集任意数量的元素,最简单的方法是使用所需的方法扩展ArrayDeque
。
这使您仍然可以使用所有普通的Deque
方法来向集合中添加元素或从集合中删除元素。
public class CircularArrayDeque<E> extends ArrayDeque<E> {
public CircularArrayDeque() {
super();
}
public CircularArrayDeque(Collection<? extends E> c) {
super(c);
}
public CircularArrayDeque(int numElements) {
super(numElements);
}
/**
* Retrieves the first element of this deque and moves it to the end, or
* returns {@code null} if this deque is empty.
*
* @return the head of this deque, or {@code null} if this deque is empty
*/
public E getNext() {
E elem = pollFirst();
if (elem != null)
addLast(elem);
return elem;
}
/**
* Retrieves the last element of this deque and moves it to the front, or
* returns {@code null} if this deque is empty.
*
* @return the tail of this deque, or {@code null} if this deque is empty
*/
public E getPrevious() {
E elem = pollLast();
if (elem != null)
addFirst(elem);
return elem;
}
}
答案 3 :(得分:-1)
如果您正在寻找C ++中的“配对”,则需要自己实现。
class Pair<K, V> {
private K object1;
private V object2;
Pair(K key, V value) {
this.object1 = key;
this.object2 = value;
}
public K getObject1() {return this.object1;}
public V getObject2() {return this.object2;}
}
// object initialization
Pair<String, Integer> p = new Pair("age", 24);
使用上面的类,您可以获得所需的功能。 如果要查找循环列表,可以使用ArrayList并修改get方法。
class CircularList<T> {
private List<T> list;
public CircularList() {
list = new ArrayList();
}
public getNext(int index) {
return list.get((index+1) % list.size());
}
}