4 changed files with 69 additions and 0 deletions
Binary file not shown.
@ -0,0 +1,48 @@ |
|||
package com.example.W8; |
|||
|
|||
// 文件名:Pair.java
|
|||
public class Pair<K, V> { |
|||
private K key; |
|||
private V value; |
|||
|
|||
// 构造方法
|
|||
public Pair(K key, V value) { |
|||
this.key = key; |
|||
this.value = value; |
|||
} |
|||
|
|||
// getter & setter
|
|||
public K getKey() { |
|||
return key; |
|||
} |
|||
|
|||
public void setKey(K key) { |
|||
this.key = key; |
|||
} |
|||
|
|||
public V getValue() { |
|||
return value; |
|||
} |
|||
|
|||
public void setValue(V value) { |
|||
this.value = value; |
|||
} |
|||
|
|||
// 交换两个Pair
|
|||
public static <K, V> void swap(Pair<K, V> p1, Pair<K, V> p2) { |
|||
K tempKey = p1.key; |
|||
V tempValue = p1.value; |
|||
|
|||
p1.setKey(p2.getKey()); |
|||
p1.setValue(p2.getValue()); |
|||
|
|||
p2.setKey(tempKey); |
|||
p2.setValue(tempValue); |
|||
} |
|||
|
|||
// 打印用
|
|||
@Override |
|||
public String toString() { |
|||
return "Pair{key=" + key + ", value=" + value + "}"; |
|||
} |
|||
} |
|||
@ -0,0 +1,21 @@ |
|||
package com.example.W8; |
|||
|
|||
// 导入Pair类
|
|||
import com.example.W8.Pair; |
|||
|
|||
public class PairTest { |
|||
public static void main(String[] args) { |
|||
Pair<String, Integer> p1 = new Pair<>("小明", 18); |
|||
Pair<String, Integer> p2 = new Pair<>("小红", 19); |
|||
|
|||
System.out.println("交换前:"); |
|||
System.out.println("p1 = " + p1); |
|||
System.out.println("p2 = " + p2); |
|||
|
|||
Pair.swap(p1, p2); |
|||
|
|||
System.out.println("\n交换后:"); |
|||
System.out.println("p1 = " + p1); |
|||
System.out.println("p2 = " + p2); |
|||
} |
|||
} |
|||
|
After Width: | Height: | Size: 32 KiB |
Loading…
Reference in new issue