杰瑞科技汇

Integer与int有何区别?

Of course! This is a fundamental concept in Java that often confuses beginners. Let's break down the difference between int and Integer in a clear, structured way.

Integer与int有何区别?-图1
(图片来源网络,侵删)

The Short Answer

  • int: A primitive data type. It's a basic building block that holds a simple integer value. It's not an object.
  • Integer: A wrapper class. It's a full-fledged object that "wraps" an int value inside it. It belongs to the Java Collections Framework and can be null.

Detailed Comparison Table

Feature int (Primitive) Integer (Object / Wrapper Class)
Type Primitive Data Type Reference Type (Object)
Purpose Stores a simple integer value. Wraps an int value to be used in object-oriented contexts.
Default Value 0 (if declared as a class member, not in a method) null (if declared as a class member, not in a method)
Can it be null? No. It cannot hold a null value. Yes. It can be null.
Memory Usage Very small, fixed size (typically 4 bytes). Larger. Stores the int value plus object overhead (e.g., header info).
Usage in Collections Cannot be used directly in collections like ArrayList, HashMap, etc. Can be used in collections. (e.g., ArrayList<Integer>)
Methods Has no methods. It's a value, not an object. Has useful methods like intValue(), parseInt(), toString(), compareTo(), etc.
Example int score = 100; Integer score = 100; or Integer score = null;

Key Differences Explained with Code Examples

Let's dive deeper into the most important distinctions.

Primitive vs. Object

  • int is a primitive. It directly stores the value in memory.
  • Integer is an object. It stores a reference to an object that, in turn, holds the int value.
// --- int ---
int primitiveInt = 50;
// The value 50 is stored directly.
// --- Integer ---
Integer integerObject = new Integer(50); // The "old" way
// Integer integerObject = 50; // The modern, "autoboxing" way
// A new Integer object is created on the heap, and its reference is stored in integerObject.

null Value

This is a critical difference that causes many NullPointerException errors.

int myInt; // Default value is 0
// myInt = null; // COMPILE ERROR! int cannot be null.
Integer myInteger = null; // This is perfectly valid.
// myInteger.intValue(); // RUNTIME ERROR! NullPointerException because you're calling a method on a null object.

This is extremely useful when you want to represent the absence of a value. For example, if you have a field age and you don't know it, Integer age = null; is much clearer than int age = 0; (which could be a valid age).

Usage in Java Collections Framework

Before Java 5 (Generics), you couldn't use primitives in collections. You had to use their wrapper classes. This is still a requirement today.

Integer与int有何区别?-图2
(图片来源网络,侵删)
// You CANNOT do this:
// List<int> myList = new ArrayList<>(); // COMPILE ERROR!
// You MUST do this:
List<Integer> myList = new ArrayList<>();
myList.add(10);      // The compiler automatically converts int 10 to Integer 10 (autoboxing)
myList.add(20);
myList.add(null);    // You can add null!
int firstValue = myList.get(0); // The compiler automatically converts Integer to int (unboxing)

Useful Methods in Integer

Since Integer is an object, it comes with helpful static methods that int does not have.

// --- String to int conversion ---
String numberStr = "123";
int num = Integer.parseInt(numberStr); // Use Integer's static method
System.out.println(num); // Output: 123
// --- int to String conversion ---
int anotherNum = 456;
String str = Integer.toString(anotherNum);
System.out.println(str); // Output: "456"
// --- Other useful methods ---
int maxInt = Integer.MAX_VALUE; // 2147483647
int minInt = Integer.MIN_VALUE; // -2147483648
int bitCount = Integer.bitCount(7); // Returns the number of one-bits (binary 111 -> 3)

Autoboxing and Unboxing (Java 5+)

To bridge the gap between primitives and objects, Java 5 introduced autoboxing and unboxing.

  • Autoboxing: Automatically converts a primitive int to its Integer wrapper object when needed.
  • Unboxing: Automatically converts an Integer object back to a primitive int when needed.

This makes the code much cleaner.

Before Autoboxing (Verbose):

int i = 10;
Integer integerObj = new Integer(i); // Manual boxing
int j = integerObj.intValue();       // Manual unboxing

With Autoboxing/Unboxing (Clean):

int i = 10;
Integer integerObj = i; // Autoboxing: int is automatically converted to Integer
int j = integerObj;     // Unboxing: Integer is automatically converted to int

This is why you can write List<Integer> list = new ArrayList<>(); list.add(5); and it works seamlessly.

When to Use Which?

Use Case Recommendation Why?
Local variables in a method int It's more memory-efficient and faster. There's no need for the overhead of an object.
Class/Instance fields Integer if the value can be absent (null), otherwise int. If "no value" is a valid state (e.g., optional field in a database), Integer is the correct choice. Otherwise, int is fine.
Method Parameters Prefer int for performance. Use Integer only if you need to pass null to signify something special. Keep method signatures simple and performant.
Keys/Values in Collections Integer Collections can only hold objects, not primitives.

Summary

  • Think of int as the simple, fast, lightweight workhorse for storing numbers.
  • Think of Integer as the more powerful, flexible, but heavier "suit" you put around the int when you need object-oriented features, like putting it in a collection or allowing it to be null.

Understanding this distinction is key to writing robust and efficient Java code.

分享:
扫描分享到社交APP
上一篇
下一篇