2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Java] length, length(), size()の違い

Last updated at Posted at 2023-02-05

要約

種類 対象 対象の例
length フィールド 配列 int[], double[], String[]
length() メソッド 文字列 String, StringBuilder
size() メソッド コレクション List, ArrayList, Set

フィールドvsメソッド

length

.lengthは配列のフィールド(情報)に直接アクセスします

//配列の長さ
int[] nums = {4, 10, 7};
nums.length;    // 3

length()

.length()はメソッドを呼び出すことで、文字列オブジェクトのフィールドメンバーにアクセスします

//文字列の長さ
String str = "abcde"
str.length();

size()

.size()はCollectionクラスで定義されているメソッドを呼び出し、要素数をカウントします

// リストを作成 
List<String> l = new ArrayList<String>();
       
// リストに要素を追加 
l.add("abcde"); 

// リストの要素数
l.size(); //5

listがの時は0が、listがnullの時はNullPointerExceptionが出力されます。

フィールドvsメソッド

一言で言えば、フィールド=情報メソッド=処理のイメージです。

  • フィールド: フィールドはクラスの中でデータの値を保管するために使用する
  • メソッド: クラスの中で特定の処理を行うために必要なプログラムをまとめたもの

詳しくはこちらの記事などを参考にしてください。


参考

2
1
0

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?