java编程基础——常用API

一些基础的java编程实现,包括Java String类、java中常用的数据结构、java数组。

1.Java String类

默认导入(如果手动导入的话输入import java.lang.Objectimport java.lang.String均可),写代码时可直接使用其中的方法。

A.常用方法

下面只列出了一些常用方法,更详细的说明可参考Java String API文档

code

//创建一个字符串,注意前后各留一个空格
String string1 = " Hello world! ";

//1.trim():去掉字符串的前后空格
String string2 = string1.trim();
System.out.println("1."+string2);

//2.indexOf():字符串中第一次出现某个元素时的下标
int i1 = string1.indexOf("l");
System.out.println("2."+i1);

//3.contains():是否含有指定的字符串
boolean b = string1.contains("word");
System.out.println("3."+b);

//4.startsWith():判断当前字符串的前缀是否是指定的字符串
boolean b2 = string1.startsWith(" He");
System.out.println("4."+b2);

//5.endsWith():判断当前字符串的后缀缀是否是指定的字符串
boolean b3 = string1.endsWith("no");
System.out.println("5."+b3);

//6.length():获取字符串的长度,空格也会计算在内
int len = string1.length();
System.out.println("6."+len);

//7.equals():比较两个字符串是否相等
//equalsIgnoreCase():与equals方法相似,但忽略大小写
//创建一个新的字符串string3,跟string比较
String string3 = "Good Game!";
boolean b4 = string3.equals(string1);
System.out.println("7."+b4);

//8.substring():从指定字符串中获取一个子串
//参数一:起始位置下标,参数二:结束位置下标,可省略,若指定则实际取到(指定值-1)的字符。注意下标从0开始
String string4 = string1.substring(3);
System.out.println("8."+string4);

//9.String():从数组c中取出元素组成字符串
//参数一:数组名称;参数二:表示起始元素的下标;参数三:表示结束元素的下标
char[] c = {'A','B','C','D'};   
String string5 = new String(c, 1, 2);
System.out.println("9."+string5);

//用字符数组value创建一个String对象
char[] value = {'a','b','c','d'};
String str4 = new String(value); //相当于String str4 = new String("abcd")
System.out.println("9."+str4);

//用比特数组创建一个String对象
byte[] strb = new byte[]{65,66};
String str6 = new String(strb);//相当于String str6 = new String("AB");
System.out.println("9."+str6);

//10.split():根据指定字符分割字符串
        String sourceStr = "1,2,3,4,5";
String[] sourceStrArray = sourceStr.split(",");
for (int i = 0; i < sourceStrArray.length; i++) {
System.out.println(sourceStrArray[i]);
}

//11.compareTo():字符串比较,对字符串内容按字典顺序进行大小比较,若当前对象比参数大则返回正整数,反之返回负整数,相等返回0
//compareToIgnore():与compareTo方法相似,但忽略大小写
String str1 = new String("abc");
String str2 = new String("ABC");
int a = str1.compareTo(str2);//a>0
int b1 = str1.compareToIgnoreCase(str2);//b1=0
System.out.println("11."+a+" "+b1);

//12.charAt():返回字符串中指定位置的字符
String str = new String("asdfzxc");
char ch = str.charAt(4);//ch = z
System.out.println("12."+ch);

//13.concat():将参数中的字符串连接到当前字符串的后面,效果等价于"+"
String str13 = "aa".concat("bb").concat("cc");
System.out.println("13."+str13);

//14.toLowerCase():返回将当前字符串中所有字符转换成小写后的新串
//toUpperCase():返回将当前字符串中所有字符转换成大写后的新串
String str14 = new String("asDF");
String str141 = str14.toLowerCase();
String str142 = str14.toUpperCase();
System.out.println("14."+str141+" "+str142);

//15.replace(char oldChar, char newChar):字符串替换,并返回一个新的字符串
//replaceFirst(String regex, String replacement)、replaceAll(String regex, String replacement)
String str15 = "asdzxcasd";
String str151 = str15.replace('a','g');
String str152 = str15.replace("asd","fgh");
String str153 = str15.replaceFirst("asd","fgh");
String str154 = str15.replaceAll("asd","fgh");
System.out.println("15."+str151+" "+str152+" "+str153+" "+str154);

输出结果依次为——

1.Hello world!
2.3
3.false
4.true
5.false
6.14
7.false
8.llo world!
9.BC
9.abcd
9.AB
1
2
3
4
5
11.32 0
12.z
13.aabbcc
14.asdf ASDF
15.gsdzxcgsd fghzxcfgh fghzxcasd fghzxcfgh

B.字符串与基本类型的转换

(1)字符串转换为基本类型

  • public static byte parseByte(String s)
  • public static short parseShort(String s)
  • public static short parseInt(String s)
  • public static long parseLong(String s)
  • public static float parseFloat(String s)
  • public static double parseDouble(String s)

int n = Integer.parseInt(“12”);
float f = Float.parseFloat(“12.34”);
double d = Double.parseDouble(“1.124”);

(2)基本类型转换为字符串

String类中提供了valueOf()方法,用作基本类型转换为字符串类型。

  • static String valueOf(char data[])
  • static String valueOf(char data[], int offset, int count)
  • static String valueOf(boolean b)
  • static String valueOf(char c)
  • static String valueOf(int i)
  • static String valueOf(long l)
  • static String valueOf(float f)
  • static String valueOf(double d)

String s1 = String.valueOf(12);
String s1 = String.valueOf(12.34);

C.字符串/字符串数组的长度

注意区分两个方法和一个属性:length()、size()、length属性。

(1) length()——针对字符串String,获取字符串的长度;
(2) size()——针对泛型集合,获取泛型集合的元素个数;
(3) length属性——针对数组,获取数组的长度;

public class Stringlen{
    public static void main(String[] args){
        String[] list={"a","bbb","cccc"};
        String a="abbbcccc";
        List<Object> array=new ArrayList();
        System.out.println(list.length);    //输出3
        System.out.println(a.length());     //输出8
        array.add(a);
        System.out.println(array.size());   //输出1
    }
}

2.java中常用的数据结构

包括由2个主要接口CollectionMap派生出来的基本数据结构类型。

Collection------>Collections
Collection------>List------>Vector\ArrayList\LinkedList
Collection------>Set------>HashSet\SortedSet...

Map------>SortedMap------>TreeMap
Map------>HashMap

A.Collection接口

由Collection接口派生的两个接口是List和Set。Collection的主要方法包括——

(1)List接口

采用线性列表的存储方式,长度可动态改变。实现List接口的常用类有LinkedList,ArrayList,Vector和Stack。


关于LinkedList——

比较LinkedList和ArrayList:

  • ArrayList底层是由数组支持,而LinkedList 是由双向链表实现的,其中的每个对象包含数据的同时还包含指向链表中前一个与后一个元素的引用。
  • LinkedList中插入元素很快,而ArrayList中插入元素很慢。
  • LinkedList中随机访问很慢,而ArrayList中随机访问很快。
  • 基于Array的List(Vector,ArrayList)适合查询,而LinkedList 适合添加,删除操作。

关于ArrayList——

ArrayList实现了可变大小的数组。其中可包含各个类型的元素,包括null,与Set不同,其中可包含重复元素。

code

// 创建一个空的数组链表对象list,list用来存放String类型的数据
ArrayList<String> list = new ArrayList<String>();

// 增加元素到list对象中
list.add("Item1");
list.add("Item2");
list.add(2, "Item3"); // 此条语句将会把“Item3”字符串增加到list的第3个位置。
list.add("Item4");

// 显示数组链表中的内容
System.out.println("The arraylist contains the following elements: " + list);

// 检查元素的位置
int pos = list.indexOf("Item2");
System.out.println("The index of Item2 is: " + pos);

// 检查数组链表是否为空
boolean check = list.isEmpty();
System.out.println("Checking if the arraylist is empty: " + check);

// 获取链表的大小
int size = list.size();
System.out.println("The size of the list is: " + size);

// 检查数组链表中是否包含某元素
boolean element = list.contains("Item5");
System.out.println("Checking if the arraylist contains the object Item5: " + element);

// 获取指定位置上的元素
String item = list.get(0);
System.out.println("The item is the index 0 is: " + item);

// 遍历arraylist中的元素

// 第1种方法: 循环使用元素的索引和链表的大小
System.out.println("Retrieving items with loop using index and size list");
for (int i = 0; i < list.size(); i++) {
    System.out.println("Index: " + i + " - Item: " + list.get(i));
}

// 第2种方法:使用foreach循环
System.out.println("Retrieving items using foreach loop");
for (String str11 : list) {
    System.out.println("Item is: " + str11);
}

// 第3种方法:使用迭代器
// hasNext(): 返回true表示链表链表中还有元素
// next(): 返回下一个元素
System.out.println("Retrieving items using iterator");
for (Iterator<String> it = list.iterator(); it.hasNext();) {
    System.out.println("Item is: " + it.next());
}

//第4种方法:把链表变为数组相关的内容进行遍历
String[] strArray=new String[list.size()];
list.toArray(strArray);
for(int i=0;i<strArray.length;i++) //这里也可以改写为  foreach(String str:strArray)这种形式
{
   System.out.println(strArray[i]);
}

// 替换元素
list.set(1, "NewItem");
System.out.println("The arraylist after the replacement is: " + list);

// 移除元素
// 移除第0个位置上的元素
list.remove(0);

// 移除第一次找到的 "Item3"元素
list.remove("Item3");
System.out.println("The final contents of the arraylist are: " + list);

// 转换 ArrayList 为 Array
String[] simpleArray = list.toArray(new String[list.size()]);
System.out.println("The array created after the conversion of our arraylist is: " + Arrays.toString(simpleArray));

输出结果——

The arraylist contains the following elements: [Item1, Item2, Item3, Item4]
The index of Item2 is: 1
Checking if the arraylist is empty: false
The size of the list is: 4
Checking if the arraylist contains the object Item5: false
The item is the index 0 is: Item1
Retrieving items with loop using index and size list
Index: 0 - Item: Item1
Index: 1 - Item: Item2
Index: 2 - Item: Item3
Index: 3 - Item: Item4
Retrieving items using foreach loop
Item is: Item1
Item is: Item2
Item is: Item3
Item is: Item4
Retrieving items using iterator
Item is: Item1
Item is: Item2
Item is: Item3
Item is: Item4
Item1
Item2
Item3
Item4
The arraylist after the replacement is: [Item1, NewItem, Item3, Item4]
The final contents of the arraylist are: [NewItem, Item4]
The array created after the conversion of our arraylist is: [NewItem, Item4]


关于Vector——

使用前手动导包import java.util.Vector;

code

//初始容量为3,增量为2
Vector<Number> v = new Vector<Number>(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
v.capacity());

v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
   (Integer)v.firstElement());
System.out.println("Last element: " +
   (Integer)v.lastElement());
if(v.contains(new Integer(3)))
   System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration<Number> vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
   System.out.print(vEnum.nextElement() + " ");
System.out.println();

输出结果——

Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector: 1 2 3 4 5.45 6.08 7 9.4 10 11 12


关于Stack——

Stack继承自Vector,实现一个后进先出的堆栈。Stack提供5个额外的方法使得Vector得以被当作堆栈使用。

(2)Set接口

Set实现的基础是Map(HashMap);Set中的元素是不能重复的,如果使用add(Object obj)方法添加已经存在的对象,则会覆盖前面的对象。主要有HashSetTreeSet两大实现类,HashSet是哈希表结构,主要利用HashMap的key来存储元素,计算插入元素的hashCode来获取元素在集合中的位置;TreeSet是红黑树结构,每一个元素都是树中的一个节点,插入的元素都会进行排序。


关于HashSet——

code

//创建HashSet集合:
Set<String> hashSet = new HashSet<String>();
System.out.println("HashSet初始容量大小:"+hashSet.size());

//元素添加:
hashSet.add("xxx");
hashSet.add("hello");
hashSet.add("world");
System.out.println("HashSet容量大小:"+hashSet.size());

//迭代器遍历:
Iterator<String> iterator = hashSet.iterator();
while (iterator.hasNext()){
String str11 = iterator.next();
System.out.println(str11);
}
//增强for循环
for(String str11:hashSet){
if("xxx".equals(str11)){
System.out.println("找到:"+str11);
}
System.out.println(str11);
}

//元素删除:
hashSet.remove("xxx");
System.out.println("HashSet元素大小:" + hashSet.size());
hashSet.clear();
System.out.println("HashSet元素大小:" + hashSet.size());

//集合判断:
boolean isEmpty = hashSet.isEmpty();
System.out.println("HashSet是否为空:" + isEmpty);
boolean isContains = hashSet.contains("hello");
System.out.println("HashSet是否包含:" + isContains);

输出结果——

HashSet初始容量大小:0
HashSet容量大小:3
world
xxx
hello
world
找到:xxx
xxx
hello
HashSet元素大小:2
HashSet元素大小:0
HashSet是否为空:true
HashSet是否包含:false

B.Map接口

采用键值对的存储方式,长度可动态改变。

Map提供key到value的映射。一个Map中不能包含相同的key,每个key只能映射一个value。Map接口提供3种集合的视图,Map的内容可以被当作一组key集合,一组value集合,或者一组key-value映射。主要实现类包括HashMap、HashTable、TreeMap等。

关于HashMap

code

//HashMap的基本使用和遍历操作
Map<String, String> map = new HashMap<String, String>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");

//第一种:普遍使用,二次取值
System.out.println("通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
 System.out.println("key= "+ key + " and value= " + map.get(key));
}

//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
 Map.Entry<String, String> entry = it.next();
 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}

//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}

//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String v1 : map.values()) {
 System.out.println("value= " + v1);
}

输出结果——

通过Map.keySet遍历key和value:
key= 1 and value= value1
key= 2 and value= value2
key= 3 and value= value3
通过Map.entrySet使用iterator遍历key和value:
key= 1 and value= value1
key= 2 and value= value2
key= 3 and value= value3
通过Map.entrySet遍历key和value
key= 1 and value= value1
key= 2 and value= value2
key= 3 and value= value3
通过Map.values()遍历所有的value,但不能遍历key
value= value1
value= value2
value= value3

C.Collections和Arrays

提供了对集合进行排序、遍历等多种算法实现。

D.比较和讨论

(1)几个常用类的区别

  • ArrayList: 元素单个,效率高,多用于查询
  • Vector: 元素单个,线程安全,多用于查询
  • LinkedList:元素单个,多用于插入和删除
  • HashMap: 元素成对,元素可为空
  • HashTable: 元素成对,线程安全,元素不可为空

(2)Vector、ArrayList和LinkedList

大多数情况下,从性能上来说ArrayList最好,但是当集合内的元素需要频繁插入、删除时LinkedList会有比较好的表现,但是它们三个性能都比不上数组,另外Vector是线程同步的。所以:

  • 如果能用数组的时候(元素类型固定,数组长度固定),请尽量使用数组来代替List;
  • 如果没有频繁的删除插入操作,又不用考虑多线程问题,优先选择ArrayList;
  • 如果在多线程条件下使用,可以考虑Vector;
  • 如果需要频繁地删除插入,LinkedList就有了用武之地;
  • 如果你什么都不知道,用ArrayList没错。

参考资料

Java 集合框架
Java 数据结构
Java基本数据结构总结
java 中几种常用数据结构

3.java数组

A.初始化

数组的初始化分为静态初始化、动态初始化和默认初始化。

// 静态初始化
int intArray2[] = new int[]{20,21,22};
// 静态初始化简化方式
int intArray3[] = {30,31,32};
// 动态初始化
int[] intArray4 = new int[3];

数组进行动态初始化时系统分配初始值的规则如下:

数组元素类型是基本类型中的整数类型(byte、short、int、long),则数组元素的值是0
数组元素类型是基本类型中的浮点类型(float、double),则数组元素的值是0.0
数组元素类型是基本类型中的字符类型(char),则数组元素的值是’\u0000’
数组元素类型是基本类型中的布尔类型(boolean),则数组元素的值是false
数组元素类型是基本类型中的引用类型(类、接口、数组),则数组元素的值是null

B.数组转Arraylist

public void arrayToList(){
    int[] buf= {1,2,3,4,5,6,7}; 
    List<Integer> list = new ArrayList<Integer>();
    for(int i : buf){
        list.add(i);
    }
}

C.寻找数组中的最值

java快速寻找一个数组的最大值或最小值, min, max,三种方法

除了自己编写各种排序算法外,还有以下方式——

1.使用 stream:将一个数组放进 stream 里面,然后直接调用 stream 里的 min 或 max 函数得到最大值或最小值。

2.使用 collection:将数组转化为对象数组,即 int 转化为 Integer (需要使用 toObject 转换), 然后调用 Collection 里面的 min或max。

3.使用 Arrays 中的 sort:Arrays 类中的 sort 可以自动将一个数组排序,排序后数组中第一个元素就是 最小值,缺点是会改变数组。

import java.util.Arrays;
import java.util.Collections;
import org.apache.commons.lang3.ArrayUtils;

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int a[] = {10, 5, 8};

        int min = Arrays.stream(a).min().getAsInt();
        System.out.println(min);

        min = Collections.min(Arrays.asList(ArrayUtils.toObject(a)));
        System.out.println(min);

        Arrays.sort(a);
        System.out.println(a[0]);
    }
}

D.一个报错

How to fix “.class expected” in Java

报错信息如下——

JT1.java:18: error: ‘.class’ expected
MetodiJT1.NumVocali(CopyArgs[])

报错原因:在调用参数为数组的函数时,传入数组时带上了[]

解决:传入数组参数时直接输入数组变量名字即可,不要带上[]

4.java获取输入

利用Scannerimport java.util.Scanner

A.常用方法

B.基本使用实例

code

//从System.in读取数字
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

//从文件myNumbers中读取long型数据
Scanner sc1 = new Scanner(new File("myNumbers"));
while (sc1.hasNextLong()) {
long aLong = sc1.nextLong();
}

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

String input1 = "1 fish 2 fish red fish blue fish";
Scanner s1 = new Scanner(input1);
s1.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s1.match();
for (int i11=1; i11<=result.groupCount(); i11++)
System.out.println(result.group(i11));
s1.close(); 

输出结果——

1
2
red
blue
1
2
red
blue

参考

Java中Scanner的nextInt(),next(),nextLine()方法总结
Java Scanner用法详解