我正在使用foreach循环使用map.get(key)打印存储在我的HashMap中的所有键及其值,但是当我尝试检索这些键时,我正在获取对象地址。我要去哪里错了?
String s="abba";
HashMap<String,Integer> map=new HashMap<String,Integer>();
for(int i=0;i<s.length();++i)
{
for(int j=i+1;j<=s.length();++j)
{
char sub[]=s.substring(i,j).toCharArray();
Arrays.sort(sub);
String s1=sub.toString();
if(!map.containsKey(s1))
map.put(s1,1);
else
map.put(s1,map.get(s1)+1); //Here also iam getting null value with map.get(s1)
}
}
for(String keyList:map.keySet())
{
System.out.println(keyList+" "+map.get(keyList));
}
如果重复按键,则该值应增加1,但仍为1。
答案 0 :(得分:0)
使用 public class st {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("abc", "2019-02-01"));
list.add(new Student("bcd", "2019-02-01"));
list.add(new Student("cdf", "2019-02-01"));
list.add(new Student("fgh", "2019-02-01"));
list.add(new Student("abc", "2019-02-02"));
list.add(new Student("bcd", "2019-02-02"));
list.add(new Student("cdf", "2019-02-02"));
list.add(new Student("fgh", "2019-02-02"));
Collections.sort(list, new Comparator() {
@Override
public int compare(Object arg0, Object arg1) {
if (!(arg0 instanceof Student)) {
return -1;
}
if (!(arg1 instanceof Student)) {
return -1;
}
Student st0 = (Student)arg0;
Student st1 = (Student)arg1;
try {
Date one = new SimpleDateFormat("yyyy-MM-dd").parse(st0.getDate());
Date two = new SimpleDateFormat("yyyy-MM-dd").parse(st1.getDate());
return one.after(two)? 1:-1;
} catch (ParseException e) {
return -1;
}
}
});
for(Student s: list) {
System.out.println(s.getDate());
}
}
}
class Student{
private String name;
private String date;
public Student(String name, String date) {
super();
this.name = name;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
代替String.valueOf(sub)
;
sub.toString()
每次都会返回相同的地址。