问题
I'm kind of new to Android and I have to make a Bluetooth connection between two PCBs. I saw a line of code in API guides and I still haven't figure out what it means. I wonder if someone can help me.
Here's that code:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
What I can't understand is Set<BluetoothDevice>
!
Why does they put something between "< >"
. I've also seen than in ArrayAdapter<String>
. What these elements do?
回答1:
That makes the Set
a Generic set. When you declare this :
Set<BluetoothDevice> pairedDevices
means the Set
object should contain only objects of type BluetoothDevice
. Using generic collections is generally recommended, because you gain the immediate benefit of type safety.
The Java Collections Framework was designed to handle objects of any type. In Java 1.4 and earlier they used java.lang.Object
as the type for any object added to the collection. You had to explicitly cast the objects to the desired type when you used them or else you would get compile-time errors.
Java Generics, introduced in Java 5, provide stronger type safety. Generics allow types to be passed as parameters to class, interface, and method declarations. For example:
Set<BluetoothDevice> pairedDevices
The <BluetoothDevice>
in this example is a type parameter. With the type parameter, the compiler ensures that we use the collection with objects of a compatible type only.
Another benefit is that we won’t need to cast the objects we get from the collection. Object type errors are now detected at compile time, rather than throwing casting exceptions at runtime.
Suggested Reading:
- Oracle's tutorial on Generics
- Using and Programming Generics in J2SE 5.0
- Generics in Java - Wiki
- Java theory and practice: Generics gotchas
- Java Generics FAQs
- Covariance and contravariance
来源:https://stackoverflow.com/questions/17897604/what-does-setelement-mean