| length() | 長さを返す |
| isEmpty() | 空文字列ならtrueを返す |
| indexOf(文字列) | 検索。見つかった位置(0~)を返す。存在しなければ-1。 |
| indexOf(文字列, 開始位置) | 検索を開始位置から行う。 |
| lastIndexOf(文字列) | 後ろから検索。見つかった位置(0~)を返す。存在しなければ-1。 |
| substring(開始, 終了) | 部分文字列を返す。開始位置から終了位置の1つ前まで。 |
| charAt(位置) | その位置の1文字を返す。 |
| contains(文字列) | 文字列を含んでいればtrueを返す。 |
| equals(文字列) | 同じならtrueを返す。 |
| replace(検索文字列,変更文字列) | 検索文字列を変更文字列に置換 |
| startsWith(文字列) | 文字列で始まるならtrueを返す。 |
| endsWith(文字列) | 文字列で終わるならtrueを返す。 |
| split(区切り文字) | 区切り文字で文字列を分割し配列で返す。 |
| matches(正規表現) | 正規表現にマッチすればtrueを返す。 |
全てstaticメソッド。
| max(数1, 数2) | 大きい方を返す |
| min(数1, 数2) | 小さい方を返す |
| abs(数) | 絶対値を返す |
| ceil(数) | 切り上げ |
| floor(数) | 切り捨て |
| round(数) | 四捨五入 |
| random() | 0~1未満の乱数を返す。例:1~6の乱数 (int)(random()*6)+1 |
文字列の連結
StringBuilder sb = new StringBuilder();
sb.append("aaa");
sb.append("bbb");
sb.append("ccc");
String s = sb.toString();
System.out.println(s);
| append(文字列) | 文字列をつなげる |
| insert(位置, 文字列) | 位置に文字列を挿入 |
| reverse() | 逆順にする |
文字列入力の例
Scanner sc = new Scanner(System.in); String str = sc.nextLine();
| nextInt() | 整数の入力 |
| nextLine() | 文字列の入力 |
ファイルの操作
File file = new File(ファイル名);
| length() | ファイルのサイズをlong型で返す |
| exists() | 存在するならtrue |
| createNewFile() | ファイル新規作成 |
| mkdir() | フォルダ新規作成 |
| delete() | ファイル削除 |
| renameTo() | ファイル名変更 |
| list() | ファイル一覧取得。Stringの配列を返す。 |
| listFiles() | ファイル一覧取得。Fileの配列を返す。 |
| getName() | ファイル名を返す。 |
| getAbsolutePath() | フルパスを返す。 |
| isDirectory() | フォルダならtrueを返す。 |
| isFile() | ファイルならtrueを返す。 |
ファイルの書き込みはFileWriterクラスで行うが、効率化のためにBufferedWriterも通常は使用する。
FileWriter fw = new FileWriter("test.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("abc\n");
bw.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"));
bw.write("abc\n");
bw.close();
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("test.txt"));
bw.write("abc");
} catch (IOException e) {
System.out.println(e.getMessage());
}finally {
if( bw != null) {
try {
bw.close();
} catch (IOException e) {
}
}
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))){
bw.write("abc");
} catch (IOException e) {
System.out.println(e.getMessage());
}
読み込みはFileReaderクラスで行うが、効率化のためにBufferedReaderクラスを使用する。
読み込むメソッドは readLine() で1行読み込んだ文字列を返す。nullが返されたら終了。
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("data.txt"));
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
}catch (IOException e) {
System.out.println(e.getMessage());
}finally {
if( br != null ) {
try {
br.close();
} catch (IOException e) {
}
}
}
try(BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
}catch (IOException e) {
System.out.println(e.getMessage());
}
FileReaderクラスの引数に Charset.forName(文字コード) で指定。
try(BufferedReader br = new BufferedReader(new FileReader("data.txt",Charset.forName("shift_jis")))) {
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
}catch (IOException e) {
System.out.println(e.getMessage());
}
一行読み込んで分割する
try(BufferedReader br = new BufferedReader(new FileReader("data.txt",Charset.forName("shift_jis")))) {
String line;
boolean first = true;
while((line = br.readLine()) != null){
if( first) { // 一行目を除外
first = false;
continue;
}
// 分割
String[] data = line.split(",");
// ひとつずつ変数に
int id = Integer.parseInt(data[0]);
String name = data[1];
int price = Integer.parseInt(data[2]);
// オブジェクトに入れる
// Shouhin s = new Shouhin(id, name, price);
// リストに追加
// list.add(s);
System.out.println(name);
}
}catch (IOException e) {
System.out.println(e.getMessage());
}
// 現在日時の取得 Date d = new Date();
// インスタンス作成 Calendar c = Calendar.getInstance();
| setTime(Date d) | dをカレンダーセット |
| getTime() | Dateで返す |
| set(年, 月, 日) | 年月日をintでセット。※月は-1した値 |
| set(年, 月, 日, 時, 分, 秒) | 年月日時分秒をintでセット。※月は-1した値 |
| get(Calendar.単位) | 単位(年月日など)を取得(下の表参照)。※月は-1した値 |
| add(Calendar.単位, 量) | 量分の単位(年月日など)を加える(下の表参照) |
| Calendar.YEAR | 年 |
| Calendar.MONTH | 月(0~11) |
| Calendar.DAY_OF_MONTH | 日 |
| Calendar.DAY_OF_WEEK | 曜日(1:日曜~7:土曜) |
| Calendar.HOUR_OF_DAY | 時 |
| Calendar.MINUTE | 分 |
| Calendar.SECOND | 秒 |
// インスタンス作成 Calendar c = Calendar.getInstance(); Date d = new Date(); // Dateをカレンダーにセット c.setTime(d); // カレンダーからDateに Date d = c.getTime(); // 特定日時の取得 c.set(2020, 6-1, 10); // 2020年6月10日 Date d = c.getTime(); // 日時の計算 c.add(Calendar.DAY_OF_MONTH, 3); // 3日後 Date d = c.getTime(); // 年のみの取得 int year = c.get(Calendar.YEAR); // 年を取得
日付の文字列化、あるいはその逆。
// Dateを文字列に
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String s = sdf.format(d);
| yyyy | 4桁の年 |
| MM | 月 |
| dd | 日 |
| HH | 時 |
| mm | 分 |
| ss | 秒 |
| E | 曜日 |
// 文字列をDateにして表示
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = sdf.parse("2021-09-17");
System.out.println(d);
} catch (ParseException e) {
System.out.println("日付形式エラー");
}
追加・削除可能な配列
| ArrayList | 配列。要素の参照が速い。 |
| LinkedList | リスト。挿入・削除が速い。 |
List<型> list = new ArrayList<型>(); Stringの例: List<String> list = new ArrayList<String>(); 右辺は型を省略可能: List<String> list = new ArrayList<>();
list.add("犬");
list.add("ねこ");
list.add("うさぎ");
String s = list.get(0); // 犬
for(String s : list){
System.out.println(s);
}
| add(要素) | 要素の追加 |
| get(番号) | その番号の要素を返す |
| set(番号,要素) | その番号を指定要素にする |
| size() | 要素数を返す |
| remove(番号) | その番号の要素を削除 |
| clear() | 全要素を削除 |
| isEmpty() | 要素が一つも無いならtrue |
| contains(要素) | その要素があるならtrue |
| indexOf(要素) | その要素があるなら番号を返す。無いなら-1。 |
| addAll(コレクション) | 引数全要素の追加 |
| sort(Comparator) | 整列 |
| subList(開始値, 終了値) | 開始値から終了値-1までの新たなリストを返す。 |
| addFirst(要素) | 要素を最初に追加 |
| addLast(要素) | 要素を最後に追加(通常のaddと同じ) |
| getFirst() | 最初の要素を返す |
| getLast() | 最後の要素を返す |
集合(重複しない配列)を表す。
| HashSet | 順番不定。 |
| TreeSet | 昇順に値を取り出せる。 |
| LinkedHashSet | 挿入順に値を取り出せる。 |
Set<型> list = new HashSet<型>(); Stringの例: Set<String> list = new HashSet<String>();
| add(要素) | 要素の追加 |
| size() | 要素数を返す |
| remove(要素) | その要素を削除 |
| clear() | 全要素を削除 |
| isEmpty() | 要素が一つも無いならtrue |
| contains(要素) | その要素があるならtrue |
| addAll(コレクション) | 全要素の追加 |
| first() | 最初の要素を返す |
| last() | 最後の要素を返す |
| ceiling(値) | 値以上の最初の要素を返す |
| floor(値) | 値以下の最初の要素を返す |
| higher(値) | 値より大きい最初の要素を返す |
| lower(値) | 値より小さい最初の要素を返す |
キーと値のペアの配列
| HashMap | 順番不定。 |
| TreeMap | キーの昇順に値を取り出せる。 |
| LinkedHashMap | 挿入順に値を取り出せる。 |
Map<キーの型,値の型> list = new HashMap<キーの型,値の型>(); キーがString、値がIntegerの例: Map<String,Integer> list = new HashMap<String,Integer>();
| put(キー,値) | 要素の追加・設定 |
| get(キー) | そのキーの要素を返す |
| size() | 要素数を返す |
| remove(キー) | そのキーの要素を削除 |
| clear() | 全要素を削除 |
| isEmpty() | 要素が一つも無いならtrue |
| containsKey(キー) | そのキーがあるならtrue |
| containsValue(値) | その値があるならtrue |
| keySet() | キーのSetを取得。 |
| values() | 値のコレクションを取得。 |
| entrySet() | Map.Entry<キーの型,値の型>のコレクションを取得。 Map.EntryはgetKey()でキーを、getValue()で値を取り出せる。 |
| firstKey() | 最初のキーを返す |
| lastKey() | 最後のキーを返す |
| ceilingKey(値) | 値以上の最初のキーを返す |
| floorKey(値) | 値以下の最初のキーを返す |
| higherKey(値) | 値より大きい最初のキーを返す |
| lowerKey(値) | 値より小さい最初のキーを返す |
List、Setの親インタフェース
| toArray() | Objectの配列にして返す |
| toArray(T[] a) | Tの配列にして返す |
Collectionの便利なメソッド集
// 要素を全て追加 Collections.addAll(list,5,8,9,3,7); // リストを逆順に Collections.reverse(list); // リストの最大値・最小値 int n = Collections.max(list); int n = Collections.min(list); // リストをシャッフル Collections.shuffle(list); // リストを昇順に整列 Collections.sort(list); // リストを任意の順に整列 Collections.sort(list, Comparatorインタフェース実装);
配列の便利なメソッド集
// 配列をリストにして返す(ただし、固定長なので追加・削除できない) List<型> list = Arrays.asList(配列); List<型> list = Arrays.asList(要素,要素,要素); // 配列をListのコンストラクタに入れて作成(追加・削除可能) List<型> list = new ArrayList<>(Arrays.asList(配列)); List<型> list = new ArrayList<>(Arrays.asList(要素,要素,要素)); // 配列を特定値で埋める Arrays.fill(配列,値);
// 配列の整列 Arrays.sort(配列); // 配列の任意順での整列 Arrays.sort(配列,Comparatorインタフェースの実装); // リストの整列 List<Integer> list = Arrays.asList(5,9,8,8,7); list.sort(Comparatorインタフェースの実装);
compareメソッドで引数の2つの要素を比較する。
※つまり、昇順の場合、「第一引数-第二引数」、降順の場合「第二引数-第一引数」を返すと良い
class MyComparator implements Comparator<Integer>{
public int compare(Integer a, Integer b) {
return a - b; // 昇順の場合。降順なら b - a
}
}
上記インタフェースの使用例
list.sort(new MyComparator()); System.out.println(list);
オブジェクトの場合(Shouhinクラスのtankaで整列)
class MyComparator implements Comparator<Shouhin>{
public int compare(Shouhin a, Shouhin b) {
return a.getTanka() - b.getTanka();
}
}
ラムダ式を使用した場合
// 昇順 list.sort((a, b)-> a - b ); // 降順 list.sort((a, b)-> b - a ); // tankaの昇順 list.sort((a, b)-> a.getTanka() - b.getTanka() ); // tankaの降順 list.sort((a, b)-> b.getTanka() - a.getTanka() );
※ (a,b)-> a - b は引数がaとb で戻り値が a - b を表す。
ブラウザ起動
String url = "http://www.yahoo.co.jp";
try {
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(url));
} catch (Exception e) {
e.printStackTrace();
}