Heim > Java > javaLernprogramm > Hauptteil

Was sind Generika in Java?

WBOY
Freigeben: 2024-08-30 16:18:36
Original
848 Leute haben es durchsucht

Generika in Java sind eine erweiterte Funktion, die die Wiederverwendbarkeit von Code und Typsicherheit ermöglicht. Die Funktionalität der Code-Wiederverwendbarkeit wird durch die Definition generischer Klassen, Schnittstellen, Konstruktoren und Methoden erreicht. Generics verwenden die Datentypdeklaration, um die Typsicherheit zu gewährleisten und so das Risiko von Laufzeitfehlern auszuschließen. Das eckige Klammersymbol „<>“ wird zur Implementierung von Generics verwendet, und Typparameter werden innerhalb der Klammern definiert. Zu diesen Typparametern gehören „T“ für Typ, „E“ für Element, „N“ für Zahl, „K“ für Schlüssel und „V“ für Wert. Ein Beispiel für eine generische Klasse mit einem Parameter vom Typ T ist „public class DemoGenericClass {…}’

 

Starten Sie Ihren kostenlosen Softwareentwicklungskurs

Webentwicklung, Programmiersprachen, Softwaretests und andere

Wie werden Generics in Java implementiert?

Generika werden mit spitzen Klammern „<>“ implementiert. und die Klammern schließen den Typparameter „T“ ein. Beispielsweise ist in der Typparameter „T“ ein Platzhalter, der angibt, dass ein Datentyp zur Laufzeit zugewiesen wird.

Eine generische Klasse kann wie folgt definiert werden:

Code:

public class MyGenericClass<T> {…}
Nach dem Login kopieren

Im Folgenden sind die Standardtypparameter aufgeführt:

  • T:Typ
  • E:Element
  • N:Nummer
  • K:Taste
  • V:Wert

Im Fall von Multiparametern werden S, U, V usw. verwendet, um den zweiten, dritten bzw. vierten Parameter zu definieren.

Generika in Java verstehen

Was ist eine Typensicherheit und wie funktioniert sie? Wie unterscheiden sich generische Klassen, Schnittstellen, Konstruktoren und Methoden von unseren regulären Klassen und Methoden, die sie wiederverwendbar machen?

Java, eine statisch typisierte Sprache, erfordert die Deklaration des Datentyps einer Variablen vor ihrer Verwendung.

Beispiel:

Code:

String myString ="eduCBA";
Nach dem Login kopieren

Im obigen Code ist „String“ der Datentyp und „myString“ die Variable, die einen Wert vom Typ String enthält.

Wenn man nun versucht, einen booleschen Wert anstelle einer Zeichenfolge zu übergeben, wie unten:

Code:

String myBooleanStr = true;
Nach dem Login kopieren

Dies führt sofort zu einem Fehler bei der Kompilierung mit der Meldung „Typkonflikt: Konvertierung von Boolean in String nicht möglich“

Ausgabe:

Was sind Generika in Java?

Wie erreicht man mit Generics die Wiederverwendbarkeit von Code?

Jetzt definieren wir eine reguläre Methode:

Code:

public static void welcome(String name){
System.out.println("welcome to " + name);
}
Nach dem Login kopieren

Diese Methode kann nur durch Übergabe eines String-Parameters aufgerufen werden.

Code:

welcome("eduCBA");
Nach dem Login kopieren

Die Ausgabe wäre „Willkommen bei eduCBA“

Allerdings kann nur ein String diese Methode aufrufen. Der Versuch, einen anderen Datentyp zu übergeben, beispielsweise eine Ganzzahl oder einen booleschen Wert, führt zur Kompilierungszeit zu einem Fehler mit der Meldung „Die Methode Welcome(String) im Typ Runner ist für die Argumente (boolean) nicht anwendbar“

Ausgabe:

Was sind Generika in Java?

Wenn man eine ähnliche Methode für einen anderen Datentyp aufrufen möchte, kann man eine neue Methode erstellen, die den erforderlichen Datentyp als Parameter akzeptiert. Diese Technik des Umschreibens von Methoden mit Parametern unterschiedlicher Datentypen wird als „Methodenüberladung“ bezeichnet. Ein Nachteil dieses Ansatzes besteht jedoch darin, dass er zu einer größeren Codegröße führen kann.

Man kann Generics auch verwenden, um die obige Methode neu zu schreiben und sie für jeden Datentyp zu verwenden, den wir benötigen.

Definieren einer generischen Methode:

Code:

public static <T> void welcome(T t){
System.out.println("it is " + t);
}
Nach dem Login kopieren

Hinweis: Hier ist „t“ ein Objekt vom Typ T. Der tatsächliche Datentyp, der zum Aufrufen der Methode verwendet wird, wird dem Typparameter „T“ zugewiesen.

Dadurch kann die Methode je nach Bedarf mit verschiedenen Datentypen wiederverwendet werden, einschließlich Zeichenfolgen, booleschen Werten, Ganzzahlen und anderen.

Code:

welcome("educba");
Integer myint = 1;
welcome(myint);
welcome(true);
Nach dem Login kopieren

Die obigen Anweisungen liefern die folgende Ausgabe:

Ausgabe:

it is educba
it is 1
it is true
Nach dem Login kopieren

Daher können wir hier durch die Verwendung von Generics unsere Methode für verschiedene Datentypen wiederverwenden.

Was sind Generika in Java?

Wie erreicht man Typsicherheit mit Generika?

Einer der Hauptunterschiede zwischen Arrays und Sammlungen besteht darin, dass Arrays nur homogene Daten speichern können, während Sammlungen heterogene Daten speichern können. Mit anderen Worten: Sammlungen können jede Art von Objekt speichern, einschließlich benutzerdefinierter Datentypen.

Hinweis: Sammlungen können nur Objekte enthalten, einschließlich benutzerdefinierter Datentypen, und keine primitiven Datentypen. Um mit primitiven Datentypen zu arbeiten, nutzen Sammlungen Wrapper-Klassen.

Now, let’s consider an ArrayList.

Code:

ArrayList myList = new ArrayList();
Nach dem Login kopieren

One can add elements of various data types, such as strings, integers, and doubles, to an ArrayList object.

Code:

myList.add("eduCBA");
myList.add(1);
myList.add(5.2);
Nach dem Login kopieren

On printing the ArrayList object, one can see that it contains the following values: [eduCBA, 1, 5.2].

Output:

Was sind Generika in Java?

To retrieve these values into variables, one needs to typecast them.

Code:

String someStr = (String)myList.get(0);
Integer someInt = (Integer)myList.get(1);
Double someFlt = (Double)myList.get(2);
Nach dem Login kopieren

If one does not typecast, it will prompt a compile-time error stating, “Type mismatch: cannot convert from Object to String”

Output:

Was sind Generika in Java?

Thus, one must typecast them to their respective types while retrieving the objects from the ArrayList. However, in real-time scenarios, an ArrayList can contain thousands of records, and manually typecasting every object may not be feasible. There is the risk of mistakenly typecasting an object to an incorrect data type. In such cases, a runtime error will occur, stating “Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at com.serviceClasess.Runner.main(Runner.java:43)”.

Was sind Generika in Java?

As there is no guarantee with regard to the type of data present inside a collection (in this case, ArrayList), they are considered unsafe to use with respect to type. Here, Generics play a role in providing type safety.

Using ArrayList with Generics:

Code:

ArrayList<String> myList = new ArrayList<String>();
Nach dem Login kopieren

The String type is specified inside the angular brackets “>” which means that this particular implementation of ArrayList can only hold String type data. If one tries to add another data type, it will simply throw a compile-time error. Here, the ArrayList has been made type-safe by eliminating its chances of adding a data type other than “String.”

Output:

Was sind Generika in Java?

Now, since one has specified the data type that is allowed to be added to the collection with the help of Generics, there is no need to typecast it while retrieving the data. One can simply retrieve the data by writing.

Code:

String someStr = myList.get(0);
Nach dem Login kopieren

Output:

Was sind Generika in Java?

How do Generics in Java make Work Easier?

  • It helps make the collections type safe and ensures the code does not fail at a later point due to any run time exception.
  • It saves the coder from having to typecast each object in the collection, which simplifies and speeds up the code development process.
  • Generics allow writing code in a way that can work with multiple data types.

What else to do with Generics in Java?

So far, we have seen how we can achieve type safety and code reusability with Generics.

In addition to type safety and code reusability, here are some other features that Generics can provide:

  • Bounded & Multiple Bounded Types
  • Type Wildcards

1. Bounded Type

In the case of a bounded type, the data type of a parameter is bounded to a particular range. The keyword “extends” helps achieve this.

For example, let’s consider a Generic class with a bounded type parameter that extends the ‘Runnable interface’:

Code:

class myGenericClass<T extends Runnable>{}
Nach dem Login kopieren

Now, while creating its object in another class:

Code:

myGenericClass<Thread> myGen = new myGenericClass<Thread>();
Nach dem Login kopieren

The above statement will execute perfectly without any errors. In the case of the bounded type, one can pass the same class type or its child class type. Also, one can bind the parameter type to an interface and pass its implementations when invoking it, as in the example above.

What happens if one uses any other type of parameter?

Code:

myGenericClass<Integer> myGen = new myGenericClass<Integer >();
Nach dem Login kopieren

In the above case, it will result in a compile-time error, stating “Bound mismatch: The type Integer is not a valid substitute for the typecast of the type myGenericClass

Output:

Was sind Generika in Java?

  • Multiple bounded types: In the case of multiple bounded types, one can bind the parameter data type to more than one type.

Example:

Code:

class myGeneric<T extends Number & Runnable>{}
Nach dem Login kopieren

In this case, one can pass any type that extends the Number class and implements the Runnable interface. However, when using multiple bounded types, a few things should be noted:

  • One cannot extend more than one class at a time.
  • One can extend any number of interfaces simultaneously, i.e., there is no limit for interfaces.
  • The class name should always come first, followed by the interface name. If not, it will result in a compile-time error.

2. Type Wildcards

The “?” (question mark) symbol represents Type Wildcards. It makes use of two main keywords:

  1. extends (to define upper bound)
  2. super (to define lower bounds).

Example:

Code:

ArrayList<? extends T> al
Nach dem Login kopieren

The ArrayList object “al” will hold any data of type T and all its subclasses.

Code:

ArrayList<? super T> al
Nach dem Login kopieren

The ArrayList object “al” will hold any data of type T and all its superclasses.

Advantages of Generics in Java

  • Flexibility: Generics allow the code to accommodate different data types with the help of Generic classes and methods.
  • Code Maintenance and Reusability: Due to Generic classes and methods, one need not rewrite the code in case of a change in requirements later, making the code easier to maintain and reuse.
  • Type Safety: Provides type safety to the collection framework by defining the data type the collection can hold beforehand; and eliminating any chances of failure at run time due to ClassCastException.
  • Eliminating the Need to Typecast: Since the data types being held by the collections are already determined, one need not typecast it at the time of retrieval. This reduces the code’s length and a coder’s effort.

Generics in Java Skills

  • To work with Generics, one should be proficient in the basics of Java.
  • One should understand how type checking and typecasting work. Thorough knowledge of other concepts such as method overloading, the relationship between parent and child classes, interfaces, and their implementations is necessary.
  • Also, it is crucial to understand the difference between primitive data types (system-defined data type) and objects (user-defined data type) when working with the collection framework.

Why use Generics in Java?

  • Using Generics makes the code more maintainable as it reduces the need to rewrite data type-specific code every time there is a change in requirements.
  • By using Generics bounded type, one can restrict the data type and, at the same time, provide flexibility to the code by defining its range.
  • Generics provide type safety, making the code less error-prone and less likely to fail at a later point.

Scope for Generics in Java

Generics scope is limited to compile time, i.e., the Generics concept is applicable only at compile time but not at run time.

Example:

Code:

ArrayList myList = new ArrayList<Integer>();
ArrayList myList = new ArrayList<Float>();
ArrayList myList = new ArrayList<Double>();
ArrayList myList = new ArrayList<Boolean>();
Nach dem Login kopieren

Here all the above four statements are the same. They will allow adding any type of data to the list object.

Conclusion

Generics renders coding easy for a coder. It diminishes the chances of encountering ClassCastException at run time by providing strong type-checking. Also, it eliminates the need for typecasting, which means less code needs to be written. It allows the development of Generic algorithms independent of the data type they are working with.

Das obige ist der detaillierte Inhalt vonWas sind Generika in Java?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!