《java语言程序设计》初步学习——各种小Demo

发现现在的天下几乎都是java的天下啊,虽然我个人对java没什么好感,但是迫于生活压力,还是学一下吧,我关注的应该主要还是web方面,所以应该学的是

java server page(JSP),所以先把javase的内容先复习复习一下吧。

我觉得通过一些demo来记语言中的一些特性和概念是比较好的,所以我总结了以下的Demo:(这只是对我个人而言比较薄弱的部分,并不能代表大部分人的看法,谢谢!)

1.一维数组与多维数组

package Demo;

public class Array {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//新建一个10元素的数组
int[] a = new int[10]; for(int i = 0;i < 10;i++){
a[i] = i;
}
System.out.println("改变前:" );
for(int i = 0;i < 10;i++){
System.out.print(a[i]+" ");
}
System.out.printf("\n");
a = reserve1(a);
System.out.println("reserve1后:");
for(int i = 0;i < 10;i++){
System.out.print(a[i]+" ");
}
System.out.printf("\n");
reserve2(a);
System.out.println("reserve2后:");
printArray(a); //二维数组的特性
int[][] a2 = {
{1,2,3},
{2,3},
{1,2,3}
};
int i;
System.out.println("a2 is " + a2.length);
for(i = 0;i < a2.length;i++){
System.out.println(i+" is "+a2[i].length);
} } //从方法中返回数组
public static int[] reserve1(int[] list){
int[] result = new int[list.length]; for(int i = 0,j = result.length-1;i < list.length;i++,j--){
result[j] = list[i];
} return result;
} //直接处理:引用传递
public static void reserve2(int[] list){
int temp; for(int i = 0,j = list.length - 1;i < list.length / 2;i++,j--){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
} //可变长的参数列表
public static void printArray(int... num){
if(num.length == 0){
System.out.println("No 参数!");
}
else{
for(int i = 0;i < num.length;i++){
System.out.print(num[i] + " ");
}
System.out.print("\n");
}
} }

2.对象与类

注意:包内访问与包外访问(包外访问加上:import packet.class_name):

 /*TTV.java*/
package Home;
import Home2.STV;
import Home2.Date; public class TTV { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
STV tv1 = new STV();
tv1.turnOn();
tv1.setChannel(30);
tv1.setVolume(3); STV tv2 = new STV();
tv2.turnOn();
tv2.channelUp();
tv2.channelUp();
tv2.volumeUp(); System.out.println("tv1's channel is" + tv1.channel
+ " and volume level is " + tv1.volumeLevel);
System.out.println("tv2's channel is" + tv2.channel
+ " and volume level is " + tv2.volumeLevel);
System.out.println("count1 = " + tv1.numplus());
System.out.println("count2 = " + tv1.numplus());
System.out.println("count3 = " + tv2.numplus()); } } /*STV.java*/
package Home2; public class STV {
public int channel = 1;
public int volumeLevel = 1;
public boolean on = false;
public static int num = 0;
public STV(){ }
public static int numplus(){
num++;
return num;
}
public void turnOn(){
on = true;
} public void turnOff(){
on = false;
} public void setChannel(int newChannel){
if(on && newChannel >= 1 && newChannel <= 120)
channel = newChannel;
} public void setVolume(int newVolumeLevel){
if(on && newVolumeLevel >= 1 && newVolumeLevel <= 7){
volumeLevel = newVolumeLevel;
}
} public void channelUp(){
if(on && channel < 120)
channel++;
} public void channelDown(){
if(on && channel >1){
channel--;
}
} public void volumeUp(){
if(on && volumeLevel < 7){
volumeLevel++;
}
} public void volumeDown(){
if(on && volumeLevel > 1){
volumeLevel--;
}
}
}

this引用:指向调用对象本身得引用名。

静态方法才能修改静态变量。

package Demo;

public class Foo {
int i = 5;
static double k = 0; public static void main(String[] args){
Foo f = new Foo();
f.setK(2.0);
System.out.println("k = " + k);
}
void setI(int i){
this.i = i;
} public static void setK(double k){
Foo.k = k;
}
}

3.继承与多态

在继承关系中,构造函数无法覆盖,类只能单一继承。注意下面例子:

注意动态绑定:

package Home2;

public class Date extends Date1{
public static void main(String[] args){
Date d1 = new Date("1"); System.out.println(d1.getNum(3)); //下面上动态绑定的结果
System.out.println("动态绑定: ");
Date1 d2 = new Date();
} public Date(){
System.out.println("(1)"); } public Date(String s){
super("4");
System.out.println(s);
} //终极函数,意味着不能再被扩展
public final int getNum(int a){
return super.getNum(a);
}
} class Date1{
public Date1(){
System.out.println("(2)");
} public Date1(String s){
System.out.println(s);
}
public int getNum(int a){
return 2*a;
} } class Date2{
public Date2(){
System.out.println("(5)");
}
}

数据和方法的可见性

类中成员的修饰符 在同一类内访问 在同一包内访问 在子类内可访问 在不同包可访问
public Y Y Y Y
protected Y Y Y -
default(不用填也不能填的默认属性 Y Y - -
private Y - - -

防止扩展和覆盖:final

终极类:public final class

终极方法:public final void m()

常量:static final PI = 3.1415926;

4.抽象类和接口

抽象类:类的设计应该确保父类包含它的子类的共同特征。有时候,一个父类设计得非常抽象,以至于它都没有任何具体的实例。抽象类的构造函数的默认属性是protected。

接口:为了定义多个类(特别是不相关的类)的共同行为。

接口与抽象类

  变量 构造方法 方法
抽象类 无限制

子类通过构造方法链调用构造方法,

抽象类不能用new操作符实例化

无限制
接口

所有的变量必须是

public static final

没有构造方法。

接口不能用new操作符实例化。

所有方法必须是公共的抽象实例方法

Java只允许为类的扩展做单一继承,但是允许使用接口做多重扩展。

抽象类Demo:

package Demo;

public class TestAnimal {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal animal = new Chicken();
eat(animal); animal = new Duck();
eat(animal);
} public static void eat(Animal animal){
System.out.println(animal.howToEat());
}
} abstract class Animal{
public abstract String howToEat();
} class Chicken extends Animal{
public String howToEat(){
return "Chicken";
}
} class Duck extends Animal{
public String howToEat(){
return "Duck";
}
}

接口Demo:

 package Demo;

 public class TestInterface {

     /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Edible stuff = new Chicken();
Edible1 stuff1 = new Broccoli();
eat(stuff); stuff = new Duck();
eat(stuff); stuff = new Broccoli();
eat(stuff);
sleep(stuff1);
} public static void eat(Edible stuff){
System.out.println(stuff.howToEat());
} public static void sleep(Edible1 stuff1){
System.out.println(stuff1.howToSleep());
}
} interface Edible{
public String howToEat(); } interface Edible1{
public String howToSleep();
} class Chicken implements Edible{
public String howToEat(){
return "Chicken";
}
} class Duck implements Edible{
public String howToEat(){
return "Duck";
}
} class Broccoli implements Edible,Edible1{
public String howToEat(){
return "Broccoli";
} public String howToSleep() {
// TODO Auto-generated method stub
return "Sleep";
}
}

5.文本I/O

一.File类的基本函数

package Demo;

public class TestFileClass {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
java。io.File file = new java.io.File("image/gif");
System.out.println("Does it exist? "+file.exists());
System.out.println("The file has " + file.length() + " bytes");
System.out.println("can it be read? " + file.canRead());
System.out.println("can it be written? " + file.canWrite());
System.out.println("Is it a directory? " + file.isDirectory());
System.out.println("Is it a file? " + file.isFile());
System.out.println("Is it absolute? " + file.isAbsolute());
System.out.println("Is it a Hidden? " + file.isHidden());
System.out.println("Absolute path is " + file.getAbsolutePath());
System.out.println("Last modified on " + new java.util.Date(file.lastModified()));
} }

二.使用PrintWriter写数据

package Demo;

public class WriteData {

    /**
* @param args
*/
public static void main(String[] args) throws Exception { //抛出异常
// TODO Auto-generated method stub
java.io.File file = new java.io.File("score.txt"); //建立文件对象
if(file.exists()){
System.out.println("File already exist");
System.exit(0);
} java.io.PrintWriter output = new java.io.PrintWriter(file); output.print("Hello!My id is ");
output.print(11365020);
output.println("!"); //close
output.close();
}
}

三.使用Scanner读数据

package Demo;

import java.util.Scanner;

public class ReadData {

    /**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
java.io.File file = new java.io.File("score.txt"); Scanner input = new Scanner(file); while(input.hasNext()){
String firname = input.next();
String mi = input.next();
int score = input.nextInt();
System.out.println(firname + mi + score);
} input.close(); }
}

注意:方法next()和nextLine()都会读取一个字符串,next()方法读取一个由分隔符分隔的字符串,但是nextLine()读取一个以行分隔符结束的行。

6.泛型

一.定义泛型类和接口

 //GenericStack.java
package Demo; public class GenericStack { private java.util.ArrayList<E> list = new java.util.ArrayList<E>(); public int getSize(){
return list.size();
} public E peek(){
return list.get(getSize() - 1);
} public void push(E o){
list.add(o);
} public E pop(){
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
} public boolean isEmpty(){
return list.isEmpty();
}
}

7.Java集合框架

关于java的集合框架,建议还是查一下文档,其实和C++的STL库差不多,只是功能上可能丰富了一点。下面介绍几个常用的:

一.Collection接口

二.Set接口

Set接口扩展了Collection接口。它没有引入新的方法或常量,只是规定Set实例不包含重复的元素。

(1).散列集HashSet

package Demo;

import java.util.*;

public class TestHashSet {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<String> set = new HashSet<String>(); //添加元素
set.add("London");
set.add("Paris");
set.add("New York");
set.add("San Franciso");
set.add("New York"); System.out.println(set); //迭代器迭代
Iterator<String> iterator = set.iterator(); while(iterator.hasNext()){
System.out.println(iterator.next().toUpperCase() + " ");
} } }

(2).链式散列集LinkedHashSet

LinkedHashSet用一个链表实现来扩展HashSet类,它支持对规则集内的元素排序。

package Demo;

import java.util.*;

public class TestLinkedHashSet {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<String> set = new LinkedHashSet<String>(); //添加元素
set.add("London");
set.add("Paris");
set.add("New York");
set.add("San Franciso");
set.add("Beijing");
set.add("New York"); System.out.println(set); //使用for-each循环
for(Object element:set)
System.out.println(element.toString().toLowerCase() + " ");
} }

(3).树形集TreeSet

package Demo;

import java.util.*;

public class TestTreeSet {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<String> set = new HashSet<String>(); set.add("London");
set.add("Paris");
set.add("New York");
set.add("San Francisco"); TreeSet<String> treeSet = new TreeSet<String>(set);
System.out.println("Sorted tree set: " + treeSet); System.out.println("first()" + treeSet.first());
System.out.println("last()" + treeSet.last());
System.out.println("headSet(): " + treeSet.headSet("New York"));
System.out.println("tailSet(): " + treeSet.tailSet("New York")); System.out.println("lower(\"P\"): " + treeSet.lower("P"));
System.out.println("higher(\"P\"): " + treeSet.higher("P"));
System.out.println("floor(\"P\"): " + treeSet.floor("P"));
System.out.println("ceiling(\"P\"): " + treeSet.ceiling("P"));
System.out.println("pollFirst(): " + treeSet.pollFirst());
System.out.println("pollLast() : " + treeSet.pollLast());
System.out.println("New tree set: " + treeSet);
} }

三.List接口

List接口增加了面向位置的操作,并且增加了一个能够双向遍历线性表的新列表迭代器。

(1).数组线性表ArrayList和链表类LinkedList

package Demo;

import java.util.*;

public class TestArrayAndLinkedList {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub List<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(1);
arrayList.add(2);
arrayList.add(3);
arrayList.add(1);
arrayList.add(4);
arrayList.add(0,10);
arrayList.add(3,30); System.out.println("A list of integers in the array list:");
System.out.println(arrayList); LinkedList<Object> linkedList = new LinkedList<Object>(arrayList);
linkedList.add(1,"red");
linkedList.removeLast();
linkedList.addFirst("green"); System.out.println("Display the linked list forward:");
ListIterator<Object> listIterator = linkedList.listIterator();
while(listIterator.hasNext()){
System.out.print(listIterator.next() + " ");
} System.out.println("Display the linked list backward:");
listIterator = linkedList.listIterator(linkedList.size());
while(listIterator.hasPrevious()){
System.out.print(listIterator.previous() + " ");
}
} }

四.向量类Vector与栈类Stack

五.队列与优先队列

Queue扩展的是Collection:

package Demo;

public class TestQueue {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
java.util.Queue<String> queue = new java.util.LinkedList<String>();
queue.offer("Oklahoma");
queue.offer("Indiana");
queue.offer("Georgia");
queue.offer("Texas"); while(queue.size() > 0)
System.out.print(queue.remove() + " ");
}
}

优先队列:PriorityQueueDemo

 package Demo;

 import java.util.*;

 public class PriorityQueueDemo {

     /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PriorityQueue<String> queue1 = new PriorityQueue<String>();
queue1.offer("Oklahoma");
queue1.offer("Indiana");
queue1.offer("Georgia");
queue1.offer("Texas"); System.out.println("Priority queue using Comparable:");
while(queue1.size() > 0){
System.out.print(queue1.remove() + " ");
} PriorityQueue<String> queue2 = new PriorityQueue<String>(4,Collections.reverseOrder());
queue2.offer("Oklahoma");
queue2.offer("Indiana");
queue2.offer("Georgia");
queue2.offer("Texas"); System.out.println("\nPriority queue using Comparable:");
while(queue2.size() > 0){
System.out.print(queue2.remove() + " ");
}
} }

六.图

图分三种,见以下代码:

package Demo;

import java.util.*;

public class TestMap {

    /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,Integer> hashMap = new HashMap<String,Integer>();
hashMap.put("Smith", 30);
hashMap.put("Anderson", 31);
hashMap.put("Lewis", 29);
hashMap.put("Cook", 29); System.out.println("Display entries in HashMap");
System.out.println(hashMap + "\n"); Map<String,Integer> treeMap = new TreeMap<String,Integer>(hashMap);
System.out.println("Display entries in ascending order of key");
System.out.println(treeMap); Map<String,Integer> linkedHashMap = new LinkedHashMap<String,Integer>(16,0.75f,true);
linkedHashMap.put("Smith", 30);
linkedHashMap.put("Anderson",31);
linkedHashMap.put("Lewis", 29);
linkedHashMap.put("Cook", 29); System.out.println("The age for " + "Lewis is " + linkedHashMap.get("Lewis").intValue()); System.out.println("\nDisplay entries in LinkedHashMap");
System.out.println(linkedHashMap);
}
}
上一篇:Java并发编程之AbstractQueuedSynchronizer源码分析


下一篇:Android——service重启