JAVA 8の研究ノート - 第3章

第3章CORE JAVAのAPI

API:アプリケーション・プログラミング・インターフェースは、あなたがサービスや機能へのアクセスを提供するクラスやインタフェース定義の基であることができます。

文字列とStringBuilderのは、テキストデータのために使用されています。 あなたが複数の値を持つ場合、配列とArrayListには使用されています

1.文字列

文字列は、基本的には文字の並びです。

文字列s =「ふわふわ」。// newでインスタンス化する必要はありません。

1)連結

  - 両方のオペランドが数値であれば、+は数値以外を意味します。

  -場合は  どちらかのオペランドが  文字列で、+は連結を意味します。

  -The式は左から右に評価されます。

文字列s =「古いです」。

S = Sで+偽。//出力oldfalse

2)不変性

Stringオブジェクトが作成されたら、充電することはできません。それは大きく、または小さくすることができない、あなたはその中に一つの文字を変更することはできません。

3)文字列プール

文字列プールはあなたのプログラムに表示されるリテラル値が含まれています。

文字列S1 =「ふわふわ」。

文字列s2 =「ふわふわ」。

S1 == S2; // trueを返します

文字列のS3 =新しい文字列( "ふわふわ");

S1 == S3; // falseを返します

4)文字列メソッド

int型の長さは()//返される型はintです

文字のcharAt(int型のインデックス)

int型のindexOf(char型CH)// -1を返したときに一致が見つかりません

int型のindexOf(CHAR CH、int型fromIndexの)

int型のindexOf(文字列str

int型のindexOf(文字列str、int型fromIndext)

文字列の部分文字列(INTたbeginIndex、int型endIndexの)// endIndexの位置にあるcharは含まれていません。最後にendIndexが欠落している場合

文字列toLowerCaseメソッド()

文字列のtoUpperCase()

boolean equals(String str) //to check whether two String object contain exactly the same characters in the same order

boolean equalsIgnoreCase(String str)

boolean startsWith(String str)

booean endsWith(String str)

boolean contains(String str)

String replace(char oldChar, char newChar)

String replace(charSequence oldChar, charSequence newChar)  // taking string as parameters

String trim()  // remove whitespace from the beginning and end of a String.

5) method chaining

"AniMal  ".trim().toLowerCase().replace('a','A');

 

2. StringBuilder

StringBuilder changes its own state and returns a reference to itself.

1) create StringBuilder

StringBuilder sb1 = new StringBuilder();

StringBuilder sb2 = new StringBuilder("animals");

StringBuilder sb3 = new StringBuilder(10);  // reserve a certain of slots for characters

StringBuilder sb4 = new StringBuilder(sb2);  // make a copy of sb2

StringBuilder sb5 = sb1;

2) important methods

same as String methods: charAt(), indexOf(String str), lengh(), substring()

StringBuilder append(String str) 

StringBuilder sb1 = new StringBuilder().append(1).append(true); //we can directly call append() without coverting parameter to String

StringBuilder insert(int offset, String str)

StringBuilder delete(int start, int end)  // the char at the end is not deleted.

StringBuilder deleteCharAt(int index)

StringBuilder reverse()

String toString() //StringBuilder used internally for performance purposes but the end results needs to be String

 

4. Equality

1) reference equality ==

String s1 = "hello";

String s2 = "hello";

String s3 = "hello ".trim();

s1 == s2;   //true, cause JVM reuses String literals

s1 == s3;   // false, cause s3 is not same as s1 at comile-time, s3 is newly-created object.

StringBuilder sb1 = new StringBuilder();

StringBuilder sb2 = new StringBuilder();

sb1 == sb2; //false, different objects

2) logical equality equals

s1.equals(s2);   //true, check logical equality

s1.equals(s3);  // true

sb1.equals(sb2);   // StringBuilder doesn't implement equals(), so it will check reference equality

 

5. Arrays

An array is an area of memory on the heap with space for a designated number of elements.

1) create an array

int[] numbers = new int[3];   // set all the elements to the default value

int numbers[] = new int[3];  //[] before or after the name, space is optional

int numbers [] = new int[3];

String[] animals = {"monkey","chimp","donkey"};

String[] bugs = animals;

System.out.println(animals.equals(bugs));  //reference equality, doesn't look at the elements inside the array.

2) use an array

animals.length;   //returns length of array

import java.util.Arrays;

int[] numbers = {6,9,1};

Arrays.sort(numbers);   //return numbers ordered in increment. {1,6,9}

Arrays.binarySearch(numbers, 7);   //returns -(2+1)

int[][] numbers= new int[][];   //compile error, cause size of array's first dimension must be set;

 

6. ArrayList

Just like a StringBuilder, ArrayList can change the size at runtime as needed.

ArrayList requires import

import java.util.ArrayList;

1) create an ArrayList

import java.util.ArrayList;

ArrayList list1 = new ArrayList();

ArrayList list2 = new ArrayList(2);

ArrayList list3 = new ArrayList(list2);  // make a copy of list2

ArrayList<String> list4 = new ArrayList<>();

List<String> list5 = new ArrayList<>();  // < wrapped class> 

ArrayList<String> list6 = new List<>(); //compile error, cause List it an interface, can NOT be instantiated

2) ArrayList methods

boolean add(E element)  // always return true

void add(int index, E element)

boolean remove(Object object)

E remove(int index)

E set(int indext, E newElement)

boolean isEmpty()

int size()

void clear()

boolean contains(Object object)

boolean equals(Object object)

 

Collections.sort(ArrayList)

 

Integer.parseInt("")   //convert string to primitive

Integer.valueOf("")   //convert string to wrapper class

autobox and unbox  //convertion between primitive and wapper class automatially

3) converting between Array and ArrayList

list.toArray();  // defaults converted to an array of class Object, isn't usually what you want

list.toArray(new String[0]);  //new array of the proper size was created, usually used

list.toArray(new String[10]);  //depends on how long

Arrays.asList(array); // convert to fixed size list, can not change the size of it

 

example 1: list -->array

import java.util.List;

List<Integer> list = new ArrayList<>();

list.add(1);

Object[] array = list.toArray();  // defaults to an array of class Object

Integer[] array = list.toArray(new Integer[0]);  // converted to an array of class Integer

 

example 2: array -->list

import java.util.List;

import java.util.Arrays;

Integer[] array = new Integer[]{1,2,3,4};

List<Integer> list = Arrays.asList(array);

list.remove(0);  // throws exception, because the size of list can not be changed

 

7. Dates and Times

Dates and times are immutable.

import java.time.*;

1) create dates and times

method signatures:

  public static LocalDate of(int year, int month, int dayofMonth)

  public static LocalDate of(int year, Month month, int dayofMonth) //Month is a special type of class called enum

  public static LocalTime of(int hour, int minutes)

  public static LocalTime of(int hour, int minutes, int seconds)

  public static LocalTime of(int hour, int minutes, int seconds, int nanos)

  LocalDateTime: 6 method signatures + 1

  public static LocalDateTime of(LocalDate, LocalTime)

example:

LocalDate date = LocalDate.of(2019, Month.JANUARY, 14);

LocalDate date = LocalDate.of(2019,5,14);

LocalDateTime dt = LocalDateTime.of(2019,5,14,15,21);

LocalDate date = LocalDate.of(2019,5,50);  // compile but throw exception

2) Manipulating Dates and Times

date.plusDays(1);

date.plusWeeks(1);

date.plusYears(1);

date.minusDays(1);

date.minusWeeks(1);

date.minusYears(1);

time.plusHours(1);

time.minusHours(1);

......

time.minusNanos(1);

time.minusDays(1);   //compile error

3) period

Five ways to create a period: no time period.

Period annually = Period.ofYears(1);

Period quarterly = Period.ofMonths(3);

Period weekly = Period.ofWeeks(1);

Period dayly = Period.ofDays(1);

Period everyYearAndAWeek = Period.of(1,0,7);

Period p = Period.ofYears(1).ofWeeks(1);  // only the last method is excuted in code chain.

date.plus(dayly);

datetime.plus(weekly);

time.plus(annually); //  try to add year to an object that only has a time. UnsupportedTemporalTypeException

4) Formatting Dates and Times

date.getYear();

date.getMonth();

date.getDayOfYear()

date.getDayOfWeek();

......

DateTimeFormatter is in the package java.time.format.  // import java.time.format.*;

DateTimeFormatter shortF = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);

DateTimeFormatter mediumF = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);

DateTimeFormatter mediumF = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM);

DateTimeFormatter mediumF = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);

DateTimeFormatter f = DateTimeFormatter.ofPattern("MMMM dd, yyyy, hh:mm"); // create your own pattern

  --M outputs 1, MM outputs 01, MMM outputs Jan, MMMM outputs January

  --d outputs 1, d outputs 01

  --yy outputs 19, yyyy outputs 2019

  --h outputs 1, hh outputs 01;

  --mm outputs 01;

The format() method is decleared on both formatter object and date/time object.

example:

LocalDate date = LocalDate.of(2019,5,14);

LocalTime time = LocalTime.of(16,43,10,10);

LocalDateTime datetime = LocalDateTime.of(date, time);

DateTimeFormatter f  = DateTimeFormatter.ofPattern("MM dd, yy");

Period weekly = Period.ofWeeks(1);

datetime = datetime.plus(weekly);

System.out.println(datetime);

System.out.println(datetime.format(f));

System.out.println(f.format(datetime));

5) parsing Dates and Times

DateTimeFormatter f = DateTimeFormatter.ofPattern("MM dd, yyyy");

LocalDate date = LocalDate.parse("05 14, 2019", f);

LocalTime time = LocalTime.parse("17:00");  // default settings

LocalDateTime dt = LocalDateTime.of(date, time);

System.out.println(dt);

 

おすすめ

転載: www.cnblogs.com/shendehong/p/11703048.html