Java 案例分析
2017-04-01 本文已影响0人
kobe_yx
case1: 创建一个person类,其中拥有两个子类,分别是Name类和Sex类。
//定义一个Name类
class Name {
//定义两个私有变量firstname,lastname,保证变量的安全性
private String firstname;
private String lastname;
//定义两个Name类,分别是不带参数的和带参数的
public Name() { }
public Name(String firstname,String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
//定义两个变量的setter和getter方法
public void set.firstname(String firstname) {
this.firstname = firstname;
}
public void set.lastname(String lastname) {
this.lastname = lastname;
}
public void getfirstname(String firstname) {
return firstname;
}
public void getlastname(String lastname) {
return lastname;
}
}
再定义一个Sex类
class Sex {
private String sex1;
private String sex2;
public Sex() { }
public Sex(String sex1,String sex2) {
this.sex1 = sex1;
this.sex2 = sex2;
}
//定义两个变量的setter和getter方法
public void set.sex1(String sex1) {
this.sex1 = sex1;
}
public void set.sex2(String sex2) {
this.sex2 = sex2;
}
public void get.sex1(String sex1) {
return sex1;
}
public void get.sex2(String sex2) {
return sex2;
}
//最后,定义一个Person类作为一个实例
public class Person {
private Name name;
private Sex sex;
public Person(Name name) {
this.name = name;
}
public Name getName() {
return name;
}
public Person(Sex sex) {
this.sex = sex;
}
public Sex getSex() {
return sex;
}
public static void main(String[] args) {
Name n = new Name("Bryant","Kobe");
Sex s = new Sex("man","woman");
Person p = new Person(n);
Person x = new Person(s);
System.out.println(p.getName().getfirstname()+p.getName().getlastname());
System.out.println(p.getSex().getSex1()+p.getSex().getSex2());
}
}
输出结果为:
KobeBryant
manwoman
至此此案例也实现成功,其中sex是我在借鉴name类的基础上添加的,也可以因此引申出其他多个类;
class2: HashMap的使用
import java.util.HashMap;
public class HelloHashMap {
public static void main(String[] args) {
int[] inputInt = {1,2,3,4,4,3,5,7,2,8,1};
char[] inputChar = {'a','b','d','g','d','a','b','c'};
System.out.println(testInteger(inputInt));
System.out.println(testChar(inputChar));
}
private static HashMap<Integer,Integer> testInteger(int[] array) {
HashMap<Integer,Integer> result = new HashMap<>();
Integer current;
for(int i = 0; i < array.length; i++) {
int num = array[i];
if(!result.containsKey(num)) {
current = 0;
} else {
current = result.get(num);
}
current++;
result.put(num,current);
}
return result;
}
private static HashMap<Character,Integer> testChar(char[] array) {
HashMap<Character,Integer> result = new HashMap<>();
Integer current;
for(int i = 0; i < array.length; i++) {
char num = array[i];
if(!result.containsKey(num)) {
current = 0;
} else {
current = result.get(num);
}
current++;
result.put(num,current);
}
return result;
}
}
线程的两种方法
package study;
/**
* Created by s on 2017/6/10.
* 单继承类
*/
public class ThreadTest extends Thread {
public void run() {
for(int i= 0; i < 10;i++) {
try{
Thread.sleep(100);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("MyThread" + i);
}
}
}