(Counting Duplicate Words) Write a program that determines and prints the number of duplicate words in a sentence. Treat uppercase and lowercase letters the same.Ignore punctuation.
((计算重复单词)编写一个程序,确定并打印句子中重复单词的数量。同样对待大写字母和小写字母。忽略标点符号)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String, Integer>();
List<String> strings = new ArrayList<String>();
String[] str = "Hello world, hello everyone. ".toLowerCase().split(" |, |\\.");
for(String s : str){
if(map.containsKey(s)){
map.put(s,map.get(s)+1);
}else{
map.put(s,1);
strings.add(s);
}
}
for(String s : strings){
if(2 <= map.get(s)){
System.out.println(s+"出现了"+map.get(s)+"次");
}
}
}
}
( Generic isEqualTo Method) Write a simple generic version of method isEqualTo that compares its two arguments with the equals method and returns true if they're equal and false otherwise. Use this generic method in a program that calls isEqualTo with a variety of built_in types, such as Object or Integer. When you run this program, are the objects passed to isEqualTo compared based on their contents or their references?
(通用isEqualTo方法)编写一个简单的通用版本的isEqual To方法,将其两个参数与equals方法进行比较,如果它们相等则返回true,否则返回false。在使用各种内置类型(如Object或Integer)调用isEqualTo的程序中使用此泛型方法。运行此程序时,传递给isEqualTo的对象是否基于其内容或引用进行比较?
public class Main {
public static void main(String[] args) {
int i_01=1;
int i_02=2;
Object o = new Object();
Object b;
System.out.println("isEqualTo(i_01,i_01)="+isEqualTo(i_01,i_01));
System.out.println("isEqualTo(i_01,i_02)="+isEqualTo(i_01,i_02));
System.out.println("isEqualTo(i_01,Object o)="+isEqualTo(i_01,o));
}
public static <I,O> boolean isEqualTo(I i, O o){
boolean b=(Object)i.hashCode()==(Object)o.hashCode();
return b;
}
}
( Generic Class Pair) Write a generic class Pair which has two type parameters F and S,each representing the type of the first and second element of the pair, respectively. Add get and set methods for the first and second elements of the pair. [ Hint: The class header should be public class Pair<F,S>]
(通用类对)编写一个通用类对,该类对具有两个类型参数F和S,每个类型参数分别表示该对的第一和第二元素的类型。为该对的第一个和第二个元素添加get和set方法。[提示:类标题应该是公共类Pair<F,S>]
public class Pair<F,S> {
private F f;
private S s;
public Pair(F x1,S x2){
f=x1;
s=x2;
}
public F getF() {
return f;
}
public S getS() {
return s;
}
public void setF(F f) {
this.f = f;
}
public void setS(S s) {
this.s = s;
}
}
public class Main {
public static void main(String[] args) {
Pair<Integer,String>pair=new Pair<Integer, String>(1,"hello");
System.out.println(pair.getF());
pair.setF(100);
System.out.println(pair.getF());
System.out.println(pair.getS());
}
}