62,614
社区成员
发帖
与我相关
我的任务
分享
package test.gt60;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test69 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person69 p1 = new Person69("p1", 11);
Person69 p2 = new Person69("p1", 11);
Person69 p3 = new Person69("p2", 11);
Person69 p4 = new Person69("p3", 11);
Person69 p5 = new Person69("p4", 11);
TestHashMapList list = new TestHashMapList();
list.add(p1.toString(), p1);
list.add(p2.toString(), p2);
list.add(p3.toString(), p3);
list.add(p4.toString(), p4);
list.add(p5.toString(), p5);
System.out.println(list.hashGet("p1_11"));
}
}
class Person69{
private String name;
private int age;
public Person69(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.name + "_" + this.age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
class TestHashMapList {
private Map<String, List<Person69>> mapValue = new HashMap(2147483);
public void add(String str, Person69 person){
if(this.mapValue.containsKey(str)){
this.mapValue.get(str).add(person);
}else {
List temp = new ArrayList(16);
temp.add(person);
this.mapValue.put(str, temp);
}
}
public List<Person69> hashGet(String str){
return this.mapValue.get(str);
}
}
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
import java.util.ArrayList;
class Person{
public Person(String name,int age){
this.name = name;
this.age = age;
}
@Override
public String toString(){
return String.format("Person[%s,%d]",name,age);
}
@Override
public boolean equals(Object obj){
if(!(obj instanceof Person)){
return false;
}
Person person = (Person)obj;
return person.name.equals(name) && person.age == age;
}
private String name;
private int age;
}
public class Test{
public static void main(String[] args){
Person p1 = new Person("李四",28);
Person p2 = new Person("张三",25);
Person p3 = new Person("张三",23);
Person p4 = new Person("王五",24);
ArrayList<Person> people = new ArrayList<>();
people.add(p1);
people.add(p2);
people.add(p3);
people.add(p4);
Person find = new Person("张三",23);
int index = people.indexOf(find);
if(index > -1){
System.out.println("找到:" + people.get(index) + " 对应位置:" + index);
}else{
System.out.println("未找到:" + find);
}
}
}