5
0

More than 1 year has passed since last update.

Javaでよく使う記述まとめ

Last updated at Posted at 2022-03-06

型を取得

double x = 9e-2;
System.out.println(((Object)x).getClass().getSimpleName()); // Double

文字列へ変換

class Main{
    // 文字列 s を受け取り、文字列の最初の文字を返す関数を作成します
    public static char stringFirst(String s){
        return s.charAt(0);
    }
    
    public static void main(String[] args){
        // R
        System.out.println(stringFirst("Recursion"));

        // a
        System.out.println(stringFirst("abcdefgh"));

        // 文字列の連結
        // stringFirst 関数の戻り値は文字なので、文字列へ変換することで文字列を連結させることができます
        System.out.println("The first letter of Recursion is " + String.valueOf(stringFirst("Recursion")));  // The first letter of Recursion is R
    }
}

Math

// x^yを計算
pow(x,y)

// √xを計算
sqrt(x)

// 小数点以下切り捨て
floor(x)

// 小数点以下切り上げ
ceil(x)
https://www.javadrive.jp/start/math/index4.html

char型+char型 = int型

public static String firstLastCharacter(String word){
    // もし述語がtrueの場合、ifステートメント内のコードを実行します。
    if(word.length() == 0){
        return "Type random words";
    }
    // もし、word.length == 0という述語がfalseと評価された場合、以下のステートメントが実行されます。
    else{
        //Javaでは以下に注意する必要があります
        //char型+char型 = int型
        //char型+str型 (オブジェクト) = str型
        return word.charAt(0) + " " + word.charAt(word.length()-1);
    }
}

双方向リスト

class Node{
    public int data;
    public Node prev;
    public Node next;

    public Node(int data){
        this.data = data;
    }
}

class DoublyLinkedList{
    public Node head;
    public Node tail;

    public DoublyLinkedList(int[] arr){
        if(arr.length <= 0){
            this.head = null;
            this.tail = this.head;
            return;
        }

        this.head = new Node(arr[0]);
        Node currentNode = this.head;
        for(int i=1; i < arr.length; i++){
            currentNode.next = new Node(arr[i]);
            currentNode.next.prev = currentNode;
            currentNode = currentNode.next;
        }
        this.tail = currentNode;
    }

    public Integer peekFront(){
        if(this.head == null) return null;
        return this.head.data;
    }

    public Integer peekBack(){
        if(this.tail == null) return this.peekFront();
        return this.tail.data;

    }

    public Node at(int index){
        Node iterator = this.head;
        for(int i=0; i < index; i++){
            iterator = iterator.next;
            if(iterator == null) return null;
        }
        return iterator;
    }

    public void enqueueFront(int data){
        if(this.head == null){
            this.head = new Node(data);
            this.tail = this.head;
        }else{
            Node node = new Node(data);
            this.head.prev = node;
            node.next = this.head;
            this.head = node;
        }
    }

    public void enqueueBack(int data){
        if(this.head == null){
            this.head = new Node(data);
            this.tail = this.head;
        }
        else{
            Node node = new Node(data);
            this.tail.next = node;
            node.prev = this.tail;
            this.tail = node;
        }
    }

    public void addNextNode(Node node, Node newNode){
        Node tempNode = node.next;
        node.next = newNode;
        newNode.next = tempNode;
        newNode.prev = node;

        if(node == this.tail) this.tail = newNode;
        else tempNode.prev = newNode;
    }

    public Integer dequeueFront(){
        if(this.head == null) return null;

        Node temp = this.head;
        this.head = this.head.next;
        if(this.head != null) this.head.prev = null;
        else this.tail = null;
        return temp.data;
    }

    public Integer dequeueBack(){
        if(this.tail == null) return null;

        Node temp = this.tail;
        this.tail = this.tail.prev;

        if(this.tail != null) this.tail.next = null;
        else this.head = null;
        return temp.data;
    }

    public void deleteNode(Node node){
        if(node == this.tail) this.dequeueBack();
        else if(node == this.head) this.dequeueFront();
        else {
            node.prev.next = node.next;
            node.next.prev = node.prev;
        }
    }

    public void reverse(){
        Node reverse = this.tail;
        Node iterator = this.tail.prev;

        Node currentNode = reverse;
        while(iterator != null){
            currentNode.next = iterator;

            iterator = iterator.prev;
            if(iterator != null) iterator.next = null;

            currentNode.next.prev = currentNode;
            currentNode = currentNode.next;

        }
        this.tail = currentNode;
        this.head = reverse;
        this.head.prev = null;
    }

    public void printInReverse(){
        String str = "";
        Node iterator = this.tail;
        while(iterator != null){
            str += iterator.data + " ";
            iterator = iterator.prev;
        }
        System.out.println("[" + str + "]");
    }

    public void printList(){
        Node iterator = this.head;
        String str = "";
        while(iterator != null){
            str += iterator.data + " ";
            iterator = iterator.next;
        }
        System.out.println("[" + str + "]");
    }
}

日付表示

import java.util.Date;
import java.text.SimpleDateFormat;

Date time = new java.util.Date();
new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(time);

string.codePointAt(index)

文字列からindex番目のコードポイントを10進数で返す。

Aを出力

System.out.println("\u0041");
System.out.println((char)0x0041);
System.out.println((char)0b1000001);
System.out.println((char)65);

(int)'A'

char 型を int 型へ型変換を行うことで、ASCII 値を取得できる。(65)

String.charAt(index)

文字列からindex番目の文字を抜き出す。

Calendar calendar = Calendar.getInstance();

Calendarクラスは演算子newではなく、getInstance()メソッドでオブジェクトを作成する。
https://recursionist.io/dashboard/course/2/lesson/212

int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;

現在の年、月の情報を取得できる。
1月は0、2月は1になるので1を足す。

string1.equals(string2)

javaで2つの値が等しいか確認するとき、String型は参照型なのでequalsメソッドを使う。
==演算子はプリミティブ型の時に使う。
https://recursionist.io/dashboard/course/2/lesson/214

LocalDateTime.now()

LocalDateTimeクラスのnow()メソッド。
現在の日時を取得できる。
https://recursionist.io/dashboard/course/2/lesson/214

LocalDateTime.now().getYear()

LocalDateTime.now().getMonthValue()

月(1~12)

LocalDateTime.now().getMonth()

月(文字列)
https://recursionist.io/dashboard/course/2/lesson/214

StringBuffer/StringBuilder

o(n)

String s = new String("");
s += "h";  //o(n)

o(1) StringBuffer/StringBuilderで時間計算量を補う。

StringBuffer s = new StringBuffer(""); 
s.append("h");  //o(1)
import java.lang.StringBuilder;

StringBuilder s = new StringBuilder(""); 
s.append("h");  //o(1)

固定配列

new int[5]{4,2,3,-1,10}

動的配列

new ArrayList<Integer>()

動的配列
配列のサイズを取得する

arr.size()

index位置の要素を取得する

arr.get(index)

末尾に追加する o(1)

arr.add(要素)

index位置に追加するo(n)

arr.add(index, 要素)

index位置の要素を削除するo(n)
arr.remove(arr.size()-1)はo(1)

arr.remove(index)

index位置の既存要素を置き換える o(1)

arr.set(index, 要素)

2つの動的配列を合わせる

list1.addAll(list2)

固定配列arrを動的配列に変換する

Arrays.asList(arr)

list(動的配列)を固定配列に変換する

list.toArray(new String[list.size()])

String型の文字列をchar型の配列に変換する

string.toCharArray()

Arrays.asList()で初期化できる

new ArrayList<Integer>(Arrays.asList(1,2,3))

reverseArrayの解き方
https://recursionist.io/dashboard/problems/submissions/220505

連想配列
データ型はラッパークラスを指定

Map<key型, value型> 変数名 = new HashMap<key型, value型>();

putメソッドでデータを追加

変数名.put(key, value);

配列の全ての要素を特定の値にする。

Arrays.fill(配列, 値);

hashmapにkeyが存在するかどうか判定するメソッド

hashmap.containsKey(key);

全てのキーを出力する。

hashmap.KeySet();

全ての値を出力する。

hashmap.values();

hashmapの値のリストをループする時の書き方

for(Integer value : hashmap.values()){}

固定配列を昇順にソートするメソッド

Arrays.sort(arr);

listの最大値を取得できる。

Collections.max(list);

Collectionsクラスのインポート

import java.util.Collections;

keyが存在すればペアの値を返し、存在しなければdefaultValueを返す。

hashmap.getOrDefault(key, defaultValue);

listを昇順にソートする

Collections.sort(list);

TreeMapはキーを自動的にソートする。

5
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0