学习笔记7

来源:互联网 发布:卧虎藏龙 罗小虎 知乎 编辑:程序博客网 时间:2024/06/06 09:07
作业。。在大本营里面写写作业。。。。感觉很诡异。。。
对应于ppt。。exercise7:Display the largest and smallest numbers for both float and double exponential notation.
public class Test2 {
 public static void main(String[] args){
  System.out.println(Double.MAX_VALUE);
  System.out.println(Double.MIN_VALUE);
  System.out.println(Float.MAX_VALUE);
  System.out.println(Float.MIN_VALUE); 
 }  
}
结果:1.7976931348623157E308
           4.9E-324
           3.4028235E38
           1.4E-45
PS:好吧。。。我承认我偷懒。。但是,学算法语言不就是为了更好的“偷懒”么?(笑)哪位用那个递归的*2方法算出来了。。麻烦告诉我声。。我自己试了试。。死循环了。。。
 
exercise 6:接着exercise5,create a new Dog reference and assign it to spot's object.Test for comparison using == and equals() for all references.
class Dog1{
 String name;
 String says;
 public Dog1(String name1,String says1){
  name=new String(name1);
  says=new String(says1);
 }
}
public class Test {
public static void main(String[] args){
 Dog1 dog1=new Dog1("spot","Ruff");
 Dog1 dog2=dog1;            //x1
 
 System.out.println(dog1.name+" "+dog1.says);
 System.out.println(dog2.name+" "+dog2.says);
 System.out.println(dog1==dog2);                   
 System.out.println(dog1.equals(dog2));
}
}
结果:spot Ruff
          spot Ruff
          true
          true
对于==和equals(),==比较的是地址,上题中x1行的操作,使得dog1和dog2指向了同一个对象(同一个地址),这里我没有操作,若改变dog1中的name和says,则dog2也会相应的改变,反之相同。equals()比较的就是具体对象的值是否相等(这个方法不适用于基本类型),在Object类(所有类的祖宗)中的equals方法是这样的
public boolean equals(Object obj) {
 return (this == obj);
    }

不难看出,在Object中,equals和“==”是等价的,都是比较两个对象的应用是否指向同一个对象(因此exercise的结果是两个true,只要==判定是true,则一般equals判定也是true),所以我们自己自定义的类,应当自己重载equals方法。比如说,String类的equals方法就是自己重载的,具体代码如下(我网上找了下。。。)

public boolean equals(Object anObject) {
 if (this == anObject) {
     return true;
 }
 if (anObject instanceof String) {
     String anotherString = (String)anObject;
     int n = count;
     if (n == anotherString.count) {
  char v1[] = value;
  char v2[] = anotherString.value;
  int i = offset;
  int j = anotherString.offset;
  while (n-- != 0) {
      if (v1[i++] != v2[j++])
   return false;
  }
  return true;
     }
 }
 return false;
    }

可以看出,String类的equals比较的就是字符串的内容是否相等,因此我们在比较两个String对象时,可以直接用equals()了,因为已经重载。。。建议大家在对于基本类型时,直接使用==或者!=吧。。使用equals()要格外小心。。。。

 
原创粉丝点击