Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Java/Scala generics

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to understand Java/Scala generics". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Generics is a technique that is often used in strongly typed programming languages. Generics are heavily used in the code of many frameworks, such as what we often see in Java:

List strList = new ArrayList (); List doubleList = new LinkedList ()

In this code, ArrayList is a generic class, and List is a generic interface class. They provide developers with a collection container for different types, to which we can add String, Double, and other various data types. Regardless of the type of internal storage, the collection container provides the same functionality to developers, such as adding add,get, etc. With generics, there is no need to create collections such as StringArrayList, DoubleArrayList, and so on, otherwise the amount of code is too large and the cost of maintenance is extremely high.

In Java, generics are generally used in three ways: generic classes, generic methods, and generic interface classes. Angle brackets are typically used to receive generic parameters.

Java generic class

If we define a MyArrayList that supports generics, this list class can simply support initialization and data writing. As long as you add after the class name, you can make the class support generics, and some properties and methods within the class can use generic type T. Of course, we can also add multiple generic parameters to this class, such as

Public class MyArrayList {private int size; T [] elements; public MyArrayList (int capacity) {this.size = capacity; this.elements = (T []) new Object [capacity];} public void set (T element, int position) {elements [position] = element;} @ Override public String toString () {String result = "; for (int I = 0; I < size) Result +) {result + = elements [I] .toString ();} return result;} public static void main (String [] args) {MyArrayList strList = new MyArrayList (2); strList.set ("first", 0); strList.set ("second", 1); System.out.println (strList.toString ());}}

We can also inherit and extend generics from the parent class. For example, there is a class definition in the Flink source code. The subclass inherits the T of the parent class and adds the generic KEY:

Public class KeyedStream extends DataStream {...}

Java generic interface class

The definition of Java generic interface class is basically the same as that of Java generic class. The following code shows the definition of the subList method in the List interface, which intercepts part of the original list.

Public interface List {... Public List subList (int fromIndex, int toIndex);}

The code to inherit and implement this interface class is as follows:

Public class ArrayList implements List {... Public List subList (int fromIndex, int toIndex) {subListRangeCheck (fromIndex, toIndex, size); return new SubList (this, 0, fromIndex, toIndex);}}

Java generic method

Generic methods can exist either in generic classes (including interface classes) or in normal classes.

The public class MyArrayList {/ / public keyword and the return value E indicate that this is a generic method / / the type E in a generic method can be different from the type T in a generic class public E processElement (E element) {. Return E;}}

As you can see from the code example above, the angle brackets between the public or private keyword and the method return value indicate that this is a generic method. The type E of a generic method can be different from the T in a generic class, or if a generic method is a member of a generic class, the generic method can either continue to use the T in the class or define a new type E.

Wildcard character

In addition to using to represent generics, there is also this form. They are called wildcards and are used to adapt to a variety of generics.

Generics summary

Summing up the generics of Java, it is found that although its syntax is sometimes dazzling, its essence is to accept different data types and enhance the reusability of the code.

We can use multiple generics in a class, each of which is generally represented by uppercase letters. Java provides some specifications for the use of uppercase letters for this purpose:

T stands for any general class.

E stands for element (Element) or exception (Exception).

K stands for key (Key).

V stands for Value and is usually used in conjunction with K, such as

Java generics provide developers with a lot of convenience, especially to ensure the simplicity of the underlying code, because the underlying code is usually encapsulated into a framework, there will be a variety of upper-level applications to call the underlying code for specific business processing, each call may involve generics. For example, both big data framework Spark and Flink require developers to process data based on generics.

The above is only a brief introduction to generics, in fact, there are still some details to pay attention to when using them.

Type erase

A legacy of Java generics is type erasure (Type Erasure). Let's take a look at the following code:

Class strListClass = new ArrayList (). GetClass (); Class intListClass = new ArrayList (). GetClass (); / / output: class java.util.ArrayListSystem.out.println (strListClass); / / output: class java.util.ArrayListSystem.out.println (intListClass); / / output: trueSystem.out.println (strListClass.equals (intListClass))

Although we used String and Integer for the declaration, the runtime information about generics was erased, and we couldn't tell the difference between strListClass and intListClass. This is because generics information exists only during the compilation phase of the code, and when the program runs on JVM, the information related to generics is erased. Type erasure doesn't matter much to most application developers, but for some framework developers, it's important to pay attention. For example, both Spark and Flink developers have used some methods to solve the type erasure problem, which has little impact on API callers.

Generics in Scala

Now that we have a basic understanding of generics in Java, let's move on to generics in Scala. In contrast, the type system of Scala is more complex, and this article only introduces some simple syntax to help readers understand some source code.

In Scala, generics are placed in square brackets []. Or we can simply understand that the original generic class of Java is now changed to [T].

We create a generic class of Stack [T] and implement two simple methods. Each member and method in the class can use the generic T. We also define generic methods, such as isStackPeekEquals [T], in which generic T can be used.

Object MyStackDemo {/ / Stack generic class class Stack [T] {private var elements: List [T] = Nil def push (x: t) {elements = x:: elements} def peek: t = elements.head} / / generic method Check whether the top of two Stack is the same def isStackPeekEquals [T] (p: Stack [T]) Q: Stack [T]): Boolean = {p.peek = = q.peek} def main (args: Array [String]): Unit = {val stack = new Stack [Int] stack.push (1) stack.push (2) println (stack.peek) val stack2 = new Stack [Int] stack2.push (2) val stack3 = new Stack [Int] stack3.push (3) println (isStackPeekEquals (stack, stack2)) println (isStackPeekEquals (stack) Stack3)} "how to understand Java/Scala generics" ends here Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report