• JAVA基础(十一)


    向下转型

    有了对象的多态性以后,内存上实际上是加载了子类特有的属性和方法的,但是由于变量声明为父类类型,导致编译时,只能调用父类中声明的属性和方法,子类特有的属性和方法不能调用。

    如何才能调用子类特有的属性和方法?

    向下转型:使用强制类型转换符

    注:此处完整代码见JAVA基础(十)

    1. Person p1 = new Man();
    2. Man m1 = (Man)p1;

     使用强转时,可能出现ClassCastException的异常

    1. Person p1 = new Man();
    2. Woman m1 = (Woman )p1;
    3. m1.goShoping(); //异常

    因为内存中没有Woman的属性和方法

    instanceof 操作符

    x instanceof A:检验x是否为类A的实例,返回值为boolean型

            要求x所属的类与类A必须是子类和父类的关系,否则编译错误。

            如果x属于类A的子类B,x instanceof A值也为true。

    1. if (p1 instanceof Person) {
    2. System.out.println("____Person____");
    3. }
    4. if (p1 instanceof Object) {
    5. System.out.println("____Object____");
    6. }

    为了避免在向下转型时出现异常,我们在向下转型前,先进行instanceof的判断,一旦返回true,就进行向下转型,否则就不执行向下转型

    1. if (p1 instanceof Woman) {
    2. System.out.println("____Woman____");
    3. Woman w2 = (Woman)p1;
    4. w2.goShopping();
    5. }
    6. if (p1 instanceof Man) {
    7. System.out.println("____Man____");
    8. Man m2 = (Man)p1;
    9. m2.earnMoney();
    10. }

    测试代码

    1. package com.xxx.java;
    2. public class PersonTest {
    3. public static void main(String[] args) {
    4. Person p = new Person();
    5. p.eat();
    6. Man m = new Man();
    7. m.eat();
    8. m.age = 25;
    9. m.earnMoney();
    10. System.out.println("*******************");
    11. //多态性
    12. Person p1 = new Man();
    13. Person p2 = new Woman();
    14. p1.eat(); //执行子类重写的方法
    15. p1.walk();
    16. System.out.println(p1.id);
    17. //p1.earnMoney();
    18. System.out.println("**********************");
    19. //Man m1 = (Man)p1;
    20. //m1.earnMoney();
    21. //m1.isSomking = true;
    22. //Woman w1 = (Woman)p1;
    23. //w1.goShopping();
    24. if (p1 instanceof Woman) {
    25. System.out.println("____Woman____");
    26. Woman w2 = (Woman)p1;
    27. w2.goShopping();
    28. }
    29. if (p1 instanceof Man) {
    30. System.out.println("____Man____");
    31. Man m2 = (Man)p1;
    32. m2.earnMoney();
    33. }
    34. if (p1 instanceof Person) {
    35. System.out.println("____Person____");
    36. }
    37. if (p1 instanceof Object) {
    38. System.out.println("____Object____");
    39. }
    40. //练习:编译通过,运行不通过:
    41. //Person p3 = new Person();
    42. //Man m3 = (Man)p3;
    43. //编译通过,运行通过
    44. Object obj = new Woman();
    45. Person p4 =(Person)obj;
    46. //编译不通过
    47. //Man m5 = new Woman();
    48. }
    49. }

    练习

    1. package com.xxx.exer;
    2. public class FieldMethodTest {
    3. public static void main(String[] args) {
    4. Sub s = new Sub();
    5. System.out.println(s.count); //20
    6. s.display(); //20
    7. //多态性
    8. Base b = s;
    9. System.out.println(b == s); //true
    10. System.out.println(b.count); //10
    11. //虚拟方法调用
    12. b.display(); //20
    13. }
    14. }
    15. class Base {
    16. int count = 10;
    17. public void display() {
    18. System.out.println(this.count);
    19. }
    20. }
    21. class Sub extends Base {
    22. int count = 20;
    23. public void display() {
    24. System.out.println(this.count);
    25. }
    26. }

    子类继承父类 

            若子类重写了父类方法,就意味着子类里定义的方法彻底覆盖了父类里的同名方法,系统              将不可能把父类里的方法转移到子类中。

            对于实例变量则不存在这样的现象,即使子类里定义了与父类完全相同的实例变量,这个实            例变量依然不可能覆盖父类中定义的实例变量

    练习2

    1. class Person {
    2. protected String name="person";
    3. protected int age=50;
    4. public String getInfo() {
    5. return "Name: "+ name + "\n" +"age: "+ age;
    6. }
    7. }
    8. class Student extends Person {
    9. protected String school="pku";
    10. public String getInfo() {
    11. return "Name: "+ name + "\nage: "+ age + "\nschool: "+ school;
    12. }
    13. }
    14. class Graduate extends Student{
    15. public String major="IT";
    16. public String getInfo() {
    17. return "Name: "+ name + "\nage: "+ age + "\nschool: "+
    18. school+"\nmajor:"+major;
    19. }
    20. }

    建立InstanceTest 类,在类中定义方法 method(Person e);

    在method中:

            (1)根据e的类型调用相应类的getInfo()方法。

            (2)根据e的类型执行:

                    如果e为Person类的对象,输出:  “a person”;

                    如果e为Student类的对象,输出: “a student”

                                                                           “a person ”

                     如果e为Graduate类的对象,输出: “a graduated student”

                                                                               “a student”

                                                                              “a person”

    1. package com.xxx.exer;
    2. public class InstanceTest {
    3. public static void main(String[] args) {
    4. InstanceTest test = new InstanceTest();
    5. test.methed(new Person());
    6. }
    7. public void methed(Person e) {
    8. System.out.println(e.getInfo());
    9. if (e instanceof Graduate) {
    10. System.out.println("“a graduated student”");
    11. }
    12. if (e instanceof Student) {
    13. System.out.println("“a student”");
    14. }
    15. System.out.println("“a person”");
    16. }
    17. }

    定义三个类,父类GeometricObject代表几何形状,子类Circle代表圆形,MyRectangle代表矩形。定义一个测试类GeometricTest,编写equalsArea方法测试两个对象的面积是否相等(注意方法的参 数类型,利用动态绑定技术),编写displayGeometricObject方法显示对象的面积(注意方法的参 数类型,利用动态绑定技术)。

    1. package com.xxx.exer1;
    2. public class GeometricObject {
    3. protected String color;
    4. protected double weight;
    5. public GeometricObject(String color, double weight) {
    6. super();
    7. this.color = color;
    8. this.weight = weight;
    9. }
    10. public String getColor() {
    11. return color;
    12. }
    13. public void setColor(String color) {
    14. this.color = color;
    15. }
    16. public double getWeight() {
    17. return weight;
    18. }
    19. public void setWeight(double weight) {
    20. this.weight = weight;
    21. }
    22. public double findArea() {
    23. return 0.0;
    24. }
    25. }
    1. package com.xxx.exer1;
    2. public class Circle extends GeometricObject {
    3. private double radius;
    4. public Circle(String color, double weight, double radius) {
    5. super(color, weight);
    6. this.radius = radius;
    7. }
    8. public double getRadius() {
    9. return radius;
    10. }
    11. public void setRadius(double radius) {
    12. this.radius = radius;
    13. }
    14. @Override
    15. public double findArea() {
    16. return 3.14 * radius * radius;
    17. }
    18. }
    1. package com.xxx.exer1;
    2. public class MyRectangle extends GeometricObject{
    3. private double width;
    4. private double height;
    5. public MyRectangle(String color, double weight, double width, double height) {
    6. super(color, weight);
    7. this.width = width;
    8. this.height = height;
    9. }
    10. public double getWidth() {
    11. return width;
    12. }
    13. public void setWidth(double width) {
    14. this.width = width;
    15. }
    16. public double getHeight() {
    17. return height;
    18. }
    19. public void setHeight(double height) {
    20. this.height = height;
    21. }
    22. @Override
    23. public double findArea() {
    24. return width * height;
    25. }
    26. }

    测试

    1. package com.xxx.exer1;
    2. public class GeometricTest {
    3. public static void main(String[] args) {
    4. GeometricTest test = new GeometricTest();
    5. Circle c1 = new Circle("white",1.0,2.3);
    6. test.displayGeometricObject(c1);
    7. Circle c2 = new Circle("white",1.0,3.3);
    8. test.displayGeometricObject(c2);
    9. System.out.println("c1和c2的面积是否相等:" + test.equalsArea(c1, c2));
    10. MyRectangle m1 = new MyRectangle("black",2.0,2.1,3.4);
    11. test.displayGeometricObject(m1);
    12. }
    13. public boolean equalsArea(GeometricObject o1,GeometricObject o2) {
    14. return o1.findArea() == o2.findArea();
    15. }
    16. public void displayGeometricObject(GeometricObject o) {
    17. System.out.println("面积为:" + o.findArea());
    18. }
    19. }

    多态是编译时行为还是运行时行为? 如何证明?

    1. package com.xxx.exer1;
    2. import java.util.Random;
    3. //面试题:多态是编译时行为还是运行时行为?
    4. //证明如下:
    5. class Animal {
    6. protected void eat() {
    7. System.out.println("animal eat food");
    8. }
    9. }
    10. class Cat extends Animal {
    11. protected void eat() {
    12. System.out.println("cat eat fish");
    13. }
    14. }
    15. class Dog extends Animal {
    16. public void eat() {
    17. System.out.println("Dog eat bone");
    18. }
    19. }
    20. class Sheep extends Animal {
    21. public void eat() {
    22. System.out.println("Sheep eat grass");
    23. }
    24. }
    25. public class InterviewTest {
    26. public static Animal getInstance(int key) {
    27. switch (key) {
    28. case 0:
    29. return new Cat ();
    30. case 1:
    31. return new Dog ();
    32. default:
    33. return new Sheep ();
    34. }
    35. }
    36. public static void main(String[] args) {
    37. int key = new Random().nextInt(3);
    38. System.out.println(key);
    39. Animal animal = getInstance(key);
    40. animal.eat();
    41. }
    42. }

    拓展问题:

    1. package com.xxx.exer1;
    2. //考查多态的笔试题目:
    3. public class InterviewTest1 {
    4. public static void main(String[] args) {
    5. Base base = new Sub();
    6. base.add(1, 2, 3);
    7. // Sub s = (Sub)base;
    8. // s.add(1,2,3);
    9. }
    10. }
    11. class Base {
    12. public void add(int a, int... arr) {
    13. System.out.println("base");
    14. }
    15. }
    16. class Sub extends Base {
    17. public void add(int a, int[] arr) {
    18. System.out.println("sub_1");
    19. }
    20. // public void add(int a, int b, int c) {
    21. // System.out.println("sub_2");
    22. // }
    23. }

    Object类的使用

    Object类是所有Java类的根父类

    如果在类的声明中未使用extends关键字指明其父类,则默认父类 为java.lang.Object类

    无属性,只有一个空参构造器

    常用方法:equals () 、toString () 、getClass () 、hashCode () 、clone () 、finalize () 、wait () 、

    notify () 、notifyAll

    ==操作符与equals方法

    = =:

            基本类型比较值:只要两个变量的值相等,即为true。

            引用类型比较引用(是否指向同一个对象):只有指向同一个对象时,==才返回true。

    用“==”进行比较时,符号两边的数据类型必须兼容(可自动转换的基本数据类型除外),否则会报错

    equals():

            所有类都继承了Object,也就获得了equals()方法。还可以重写。 

                    只能比较引用类型,其作用与“==”相同,比较是否指向同一个对象。

            源码:

    1. public boolean equals(Object obj) {
    2. return (this == obj);
    3. }

            特例:当用equals()方法进行比较时,对类File、String、Date及包装类 (Wrapper Class )                     来说,是比较类型及内容而不考虑引用的是否是同一个对象

            原因:在这些类中重写了Object类的equals()方法

    1. //比较基本数据类型
    2. int i = 10;
    3. int j = 10;
    4. double d = 10.0;
    5. System.out.println(i == j); //true
    6. System.out.println(i == d); //true
    7. boolean b = true;
    8. //System.out.println(i == b); 报错
    9. char c = 10;
    10. System.out.println(i == c); //true
    11. char c1 = 'A';
    12. char c2 = 65;
    13. System.out.println(c1 == c2);
    14. //比较引用数据类型
    15. Customer cust1 = new Customer("Tom",21);
    16. Customer cust2 = new Customer("Tom",21);
    17. System.out.println(cust1 == cust2);
    18. String str1 = new String("abc");
    19. String str2 = new String("abc");
    20. System.out.println(str1 == str2);
    21. System.out.println("*************************");
    22. //equals的使用
    23. System.out.println(cust1.equals(cust2));
    24. System.out.println(str1.equals(str2)); //String重写了

    重写equals方法

    1. @Override
    2. //比较两个对象的name和age是否相同
    3. public boolean equals(Object obj) {
    4. if (this == obj) {
    5. return true;
    6. }
    7. if (obj instanceof Customer) {
    8. Customer cust = (Customer) obj;
    9. return this.age == cust.age && this.name.equals(cust);
    10. }
    11. return false;
    12. }

    也可以使用Eclipse提供的一键生成equals方法

    1. //自动生成的equals
    2. @Override
    3. public boolean equals(Object obj) {
    4. if (this == obj)
    5. return true;
    6. if (obj == null)
    7. return false;
    8. if (getClass() != obj.getClass())
    9. return false;
    10. Customer other = (Customer) obj;
    11. return age == other.age && Objects.equals(name, other.name);
    12. }

    重写equals()方法的原则

    对称性:如果x.equals(y)返回是“true” ,那么y.equals(x)也应该返回是 “true”。

    自反性:x.equals(x)必须返回是“true”。

    传递性:如果x.equals(y)返回是“true” ,而且y.equals(z)返回是“true” , 那么z.equals(x)也应该                    返回是“true”。

    一致性:如果x.equals(y)返回是“true” ,只要x和y内容一直不变,不管你 重复x.equals(y)多少次,                返回都是“true”。

    任何情况下,x.equals(null),永远返回是“false” ;

    x.equals(和x不同类型的对象)永远返回是“false”。

    ==和equals的区别

    == 既可以比较基本类型也可以比较引用类型。对于基本类型就是比较值,对于引用类型 就是比较内存地址

    equals的话,它是属于java.lang.Object类里面的方法,如果该方法没有被重写过默认也 是

    ==;我们可以看到String等类的equals方法是被重写过的,而且String类在日常开发中 用的比较多,久而久之,形成了equals是比较值的错误观点。

    具体要看自定义类里有没有重写Object的equals方法来判断。

    通常情况下,重写equals方法,会比较类中的相应属性是否都相等。

    toString() 方法

    toString()方法在Object类中定义,其返回值是String类型,返回类名和它的引用地址。

    当我们输出一个对象的引用时,实际上就是调用当前对象的toString()

            因为print方法若输出一个对象会调用valueOf方法,而valueOf方法只要该对象不为空就调用             toString方法

    Object类中的源码

    1. public String toString() {
    2. return getClass().getName() + "@" + Integer.toHexString(hashCode());
    3. }

    像String Date File 包装类 等 都重写了Object类的toString方法

    自定义类也可以重写toString方法

    1. public String toString() {
    2. return "Customer[name = " + name + " age = " + age + "]";
    3. }

    也可以自动生成:

    1. @Override
    2. public String toString() {
    3. return "Customer [name=" + name + ", age=" + age + "]";
    4. }

    测试 

    1. Customer cust1 = new Customer("Tom",21);
    2. System.out.println(cust1.toString());//输出地址值
    3. System.out.println(cust1); //输出地址值
    4. String str = new String("MM");
    5. System.out.println(str);

    练习

    定义两个类,父类GeometricObject代表几何形状,子类Circle代表圆形。

     写一个测试类,创建两个Circle对象,判断其颜色是否相等;利用equals方法判断其半径是否     相等;利用 toString()方法输出其半径。

    1. package com.xxx.exer3;
    2. public class GeometricObject {
    3. protected String color;
    4. protected double weight;
    5. public GeometricObject() {
    6. super();
    7. this.color = "white";
    8. this.weight = 1.0;
    9. }
    10. public GeometricObject(String color, double weight) {
    11. super();
    12. this.color = color;
    13. this.weight = weight;
    14. }
    15. public String getColor() {
    16. return color;
    17. }
    18. public void setColor(String color) {
    19. this.color = color;
    20. }
    21. public double getWeight() {
    22. return weight;
    23. }
    24. public void setWeight(double weight) {
    25. this.weight = weight;
    26. }
    27. }
    1. package com.xxx.exer3;
    2. public class Circle extends GeometricObject {
    3. private double radius;
    4. public Circle() {
    5. super();
    6. radius = 1.0;
    7. }
    8. public Circle(double radius) {
    9. super();
    10. this.radius = radius;
    11. }
    12. public Circle(double radius,String color,double weight) {
    13. super(color,weight);
    14. this.radius = radius;
    15. }
    16. public double getRadius() {
    17. return radius;
    18. }
    19. public void setRadius(double radius) {
    20. this.radius = radius;
    21. }
    22. public double findArea() {
    23. return 3.14 * radius * radius;
    24. }
    25. @Override
    26. public boolean equals(Object obj) {
    27. if(this == obj) {
    28. return true;
    29. }
    30. if(obj instanceof Circle) {
    31. Circle c = (Circle)obj;
    32. return this.radius == c.radius;
    33. }
    34. return false;
    35. }
    36. @Override
    37. public String toString() {
    38. return "Circle [radius=" + radius + "]";
    39. }
    40. }
    1. package com.xxx.exer3;
    2. public class CircleTest {
    3. public static void main(String[] args) {
    4. Circle c1 = new Circle(2.3);
    5. Circle c2 = new Circle(2.3, "white", 2.0);
    6. System.out.println("颜色是否相同:" + c1.getColor().equals(c2.getColor()));
    7. System.out.println("半径是否相同:" + c1.equals(c2));
    8. System.out.println(c1); //调用toString方法
    9. System.out.println(c2.toString());
    10. }
    11. }

    单元测试(JUnit)

    使用方法:

    1、右键当前项目文件夹——Build Path——Add Libraries

     选择JUnit——Next

     选择JUnit4——Finish

    2、创建一个Java类进行单元测试 

    要求:

            此时的Java类要求是Public的;

            此类提供Public的无参构造器

    3、此类中声明一个单元测试方法:

    要求:

            此方法权限是public的

            没有返回值

            没有形参

    4、此单元测试方法上需要声明注解:@Test,并导入相关java包:org.junit.Test

    5、声明号单元测试方法以后,就能在方法体内测试相关代码

    6、写完代码以后,左键双击方法名,右键run as JUnitTest

     如果执行结果没有任何异常,为绿条

     如果执行结果出现异常,红条

    测试

    1. package com.xxx.java2;
    2. import java.sql.Date;
    3. import org.junit.Test;
    4. public class JUnitTest {
    5. int num;
    6. public void show() {
    7. num = 20;
    8. System.out.println("show()");
    9. }
    10. @Test
    11. public void testEquals() {
    12. String s1 = "A";
    13. String s2 = "A";
    14. System.out.println(s1.equals(s2));
    15. Object obj = new String();
    16. Date date = (Date)obj;
    17. System.out.println(num);
    18. show();
    19. }
    20. @Test
    21. public void testToString() {
    22. String s2 = "A";
    23. System.out.println(s2.toString());
    24. }
    25. }

    包装类(Wrapper)的使用

    针对八种基本数据类型定义相应的引用类型—包装类(封装类)

    有了类的特点,就可以调用类中的方法,Java才是真正的面向对象

    基本数据类型包装成包装类的实例——装箱

    通过包装类的构造器实现:

    1. int i = 500;
    2. Integer t = new Integer(i);

     还可以通过字符串参数构造包装类对象:

    1. Float f = new Float(“4.56”);
    2. Long l = new Long(“asdf”); //NumberFormatException

    获得包装类对象中包装的基本类型变量 ---拆箱

    调用包装类的.xxxValue()方法:

    1. Integer in1 = new Integer(12);
    2. int i1 = in1.intValue();
    3. System.out.println(i1 + 1);

    JDK1.5之后,支持自动装箱,自动拆箱。但类型必须匹配。

    1. //自动装箱:
    2. int num2 = 10;
    3. Integer in1 = num2;
    1. //自动拆箱
    2. int num3 = in1;

    包装类转换成字符串与基本数据类型转换成字符串

    1. float f1 = 12.3f;
    2. String str2 = String.valueOf(f1);
    3. Double d1 = new Double(12.4);
    4. String str3 = String.valueOf(d1);

    除此之外基本数据类型还可以通过字符串拼接来转换

    1. int num1 = 10;
    2. String str1 = num1 + "";

    字符串转换成基本数据类型

    通过包装类的构造器实现:

    1. String str = "123"
    2. int i = new Integer(str);

    通过包装类的parseXxx(String s)静态方法:

    1. String str2 = "true";
    2. boolean b1 = Boolean.parseBoolean(str2);
    3. System.out.println(b1);

    相关代码

    1. package com.xxx.java2;
    2. import org.junit.Test;
    3. public class WrapperTest {
    4. @Test
    5. public void test1() {
    6. // 基本数据类型——>包装类:
    7. int num = 10;
    8. Integer in1 = new Integer(num); // 传入int
    9. System.out.println(in1.toString());
    10. Integer in2 = new Integer("123"); // 传入String
    11. System.out.println(in2.toString());
    12. // 报异常
    13. // Integer in3 = new Integer("123abc"); //不能传入非数字
    14. // System.out.println(in3.toString());
    15. Float f1 = new Float(12.3f); // 传入float
    16. Float f2 = new Float(12.3f); // 传入double
    17. Float f3 = new Float("12.3"); // 传入String
    18. System.out.println(f1);
    19. System.out.println(f2);
    20. System.out.println(f3);
    21. Boolean b1 = new Boolean(true);
    22. Boolean b2 = new Boolean("true");
    23. // 不会报错
    24. Boolean b3 = new Boolean("tRuE");
    25. Boolean b4 = new Boolean("true123"); // 只有传入的字符串不是ture(忽略大小写都为false)
    26. Order order = new Order();
    27. System.out.println(order.isMale); // false
    28. System.out.println(order.isFemale); // null
    29. }
    30. // 包装类转换为基本数据类型
    31. @Test
    32. public void test2() {
    33. Integer in1 = new Integer(12);
    34. int i1 = in1.intValue();
    35. System.out.println(i1 + 1);
    36. Float f1 = new Float(12.3);
    37. float f2 = f1.floatValue();
    38. System.out.println(f2 + 1);
    39. }
    40. @Test
    41. public void test3() {
    42. // 包装类的使用
    43. int num1 = 10;
    44. // Integer in = new Integer(num1);
    45. // method(in);
    46. // JDK5.0新增自动装箱与拆箱
    47. method(num1);
    48. // 自动装箱:
    49. int num2 = 10;
    50. Integer in1 = num2;
    51. boolean b1 = true;
    52. Boolean b2 = b1;
    53. // 自动拆箱
    54. System.out.println(in1.toString());
    55. int num3 = in1;
    56. }
    57. public void method(Object obj) {
    58. System.out.println(obj);
    59. }
    60. @Test
    61. public void test4() {
    62. // 基本数据类型、包装类——>String类型
    63. // 方式1:
    64. int num1 = 10;
    65. String str1 = num1 + "";
    66. // 方式2:
    67. float f1 = 12.3f;
    68. String str2 = String.valueOf(f1);
    69. Double d1 = new Double(12.4);
    70. String str3 = String.valueOf(d1);
    71. System.out.println(str2);
    72. System.out.println(str3);
    73. }
    74. @Test
    75. public void test5() {
    76. // String类型——>基本数据类型、包装类
    77. String str1 = "123";
    78. //错误情况
    79. //int num1 = (int)str1;
    80. //Integer in = (Integer)str1;
    81. //调用包装类的parsexxx方法
    82. int num2 = Integer.parseInt(str1);
    83. System.out.println(num2 + 1);
    84. String str2 = "true";
    85. boolean b1 = Boolean.parseBoolean(str2);
    86. System.out.println(b1);
    87. }
    88. }
    89. class Order {
    90. boolean isMale;
    91. Boolean isFemale;
    92. }

     总结:基本类型、包装类与String类间的转换

    面试题

    1

    1. Object o1 = true ? new Integer(1) : new Double(2.0);
    2. System.out.println(o1); //1.0

    解析:

            三元运算符自动类型转换

            多态虚拟方法调用

    2

    1. Object o2;
    2. if (true)
    3. o2 = new Integer(1);
    4. else
    5. o2 = new Double(2.0);
    6. System.out.println(o2); //1

    3

    1. Integer i = new Integer(1);
    2. Integer j = new Integer(1);
    3. System.out.println(i == j);//false
    4. Integer m = 1;
    5. Integer n = 1;
    6. System.out.println(m == n);//true
    7. Integer x = 128;
    8. Integer y = 128;
    9. System.out.println(x == y);//false

    解析:

            -128到127为常用数,在Integer内定义了一个IntegerCathe,里面定义了一个Intefer[ ],保              存了这个范围的整数,如有需要使用该数组的元素,不需要new,提高了效率,所以m == n

            而128不在这个范围,需要在new一个新的对象,地址不同自然返回false

    练习:

    利用Vector代替数组处理:从键盘读入学生成绩(以负数代表输入结束),找出 最高分,并输出学生成绩等级。

            提示:数组一旦创建,长度就固定不变,所以在创建数组前就需要知道它的 长度。而向量                         类java.util.Vector可以根据需要动态伸缩。

            创建Vector对象:Vector v=new Vector();

            给向量添加元素:v.addElement(Object obj); //obj必须是对象

            取出向量中的元素:Object obj=v.elementAt(0);

                    注意第一个元素的下标是0,返回值是Object类型的。

            计算向量的长度:v.size();

            若与最高分相差10分内:A等;20分内:B等; 30分内:C等;其它:D等

    1. package com.xxx.exer4;
    2. import java.util.Scanner;
    3. import java.util.Vector;
    4. public class ScoreTest {
    5. public static void main(String[] args) {
    6. Scanner scan = new Scanner(System.in);
    7. Vector v = new Vector();
    8. int maxScore = 0;
    9. for (;;) {
    10. System.out.println("请输入学生成绩(以负数代表输入结束)");
    11. int score = scan.nextInt();
    12. if (score < 0) {
    13. break;
    14. }
    15. if (score > 100) {
    16. System.out.println("输入的数据非法,请重新输入");
    17. continue;
    18. }
    19. v.addElement(score);
    20. if (maxScore < score) {
    21. maxScore = score;
    22. }
    23. }
    24. char level;
    25. for (int i = 0; i < v.size(); i++) {
    26. Object obj = v.elementAt(i);
    27. int score = (int)obj;
    28. if (maxScore - score <= 10) {
    29. level = 'A';
    30. } else if(maxScore - score <= 20){
    31. level = 'B';
    32. }else if(maxScore - score <= 30){
    33. level = 'C';
    34. }else {
    35. level = 'D';
    36. }
    37. System.out.println("student——" + i + ",score is " + score + ",level is " + level);
    38. }
    39. }
    40. }

  • 相关阅读:
    四面阿里巴巴回来分享面经总结,定级P7架构师
    构建高可用性的 SQL Server:Docker 容器下的主从同步实现
    Java中string、int、char之间互相转换
    KiB、MiB与KB、MB的区别
    【GIT】:一文快速了解什么是GIT
    【数据分享】《中国法律年鉴》1987-2022
    python实操-----图书管理系统
    MYSQL基础——函数
    【华为校招】【校招】【Java】污染水域(DFS)
    VSCode中配置C/C++环境
  • 原文地址:https://blog.csdn.net/m0_56413004/article/details/126112919