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 Java and Scala collections are converted to each other

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

Share

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

This article focuses on "how Java and Scala collections are transformed into each other". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how Java and Scala collections are transformed into each other.

Catalogue

Mutual conversion between Java and Scala collections

Scala and java transfer each other

Set comparison between Java and Scala

I. Java collection

1. Collection= > Set API

2. Collection= > List API

3. Map interface

II. Scala set

1 、 Seq

2 、 Set

3 、 Map

Mutual conversion between Java and Scala collections

In scala, to call a method of java, you usually need to pass the corresponding parameters. The following is the corresponding table for the conversion between scala and java

Conversion between Iterator java.util.IteratorIterator java.util.EnumerationIterable java.lang.IterableIterable java.util.Collectionmutable.Buffer java.util.Listmutable.Set java.util.Setmutable.Map java.util.Mapmutable.ConcurrentMap java.util.concurrent.ConcurrentMapscala and java import collection.JavaConverters._ import collection.mutable._ val map = Map ("k"-> "v") / / converted to java val javaMap = map.asJava / / converted to scala javaMap.asScala

Note: within Scala, these transformations are done through a series of "wrapper" objects that forward the corresponding method calls to the underlying container object. So the container does not copy between Java and Scala.

A noteworthy feature is that if you convert a Java container to its corresponding Scala container, and then convert it back to the same Java container, you end up with exactly the same container object as in the beginning.

There are some Scala container types that can be converted to corresponding Java types, but they do not have the ability to convert the corresponding Java types to Scala types

Seq = > java.util.Listmutable.Seq = > java.util.ListSet = > java.util.SetMap = > java.util.Map

Because Java does not distinguish between mutable container immutable container types, although you can convert scala.immutable.List to java.util.List, all modification operations will throw "UnsupportedOperationException"

Scala > jul = List (1,2,3). AsJavajul: java.util.List [Int] = [1,2,3] scala > jul.add (7) java.lang.UnsupportedOperationException at java.util.AbstractList.add (AbstractList.java:131) Java and Scala set comparison I. Java set

Object-oriented language embodies things in the form of objects in order to store multiple objects. Arrays alone are not enough to solve the problem, and it is extremely inconvenient to manipulate objects. Arrays cannot store different objects.

A collection is like a container in which references to multiple objects can be placed into the container dynamically.

Collection collection: a collection of objects that are not stored in the order in which they are added, and the contents of the elements in the collection can be repeated.

Save one object at a time

1. Collection= > Set API

Elements are not added in the order in which they are added (out of order), and collections of the same elements (content rather than address) cannot be added repeatedly.

> HashSet

Set collections implemented using hashing algorithms

Deduplication rule: the equals of two objects is true, and the hash codes of two objects are equal

If you want your custom object to repeat, you need to override equals and hashCode

> LinkedSet

> TreeSet

The order of addition is out of order and cannot be repeated

Note that different types cannot be added when adding elements, because they will be compared, and different types of elements cannot be compared.

1. The custom class should implement the Comparable interface, implement and override the method.

Deduplication rule: compareTo returns 0

2. Write a concrete class that implements the Comparator interface, overrides the compare method, and associates the comparator with the TreeSet

For Set collections implemented using trees, the underlying layer is implemented through binary trees (= > so the added data appears to be in order when traversed)

2. Collection= > List API

Elements in the order in which they are added (in order), a collection of the same elements can be added repeatedly.

> ArrayList

List collections implemented using arrays

> LinkedList

List collections implemented using linked lists

> Vector

Vector: is a thread-safe dynamic array. At the bottom is the array structure, which is initialized to an array of length 10. If the capacity is full, it will be expanded by 2.0x. In addition to supporting foreach and Iterator traversal, Enumeration iteration is also supported.

ArrayList and LinkedList

1.ArrayList implements the data structure based on dynamic array and LinkedList based on linked list.

two。 Feel better than LinkedList for random access to get and set,ArrayList, because LinkedList moves the pointer.

3. Add and remove,LinedList are more advantageous for adding and deleting operations, because ArrayList moves data. It depends on the actual situation. If only a single piece of data is inserted or deleted, ArrayList is faster than LinkedList. But if the batch randomly inserts and deletes data, the speed of LinkedList is much better than that of ArrayList. Because every time ArrayList inserts a piece of data, it moves the insertion point and all data after it.

The difference between Arraylist,LinkedList,Vector

ArrayList: is a thread-unsafe dynamic array. The underlying layer is the array structure. After JDK1.7, the array is initialized to an empty array, and when the first element is added, it is initialized to an array of length 10. If the capacity is full, the capacity is expanded by 1.5 times. Support for foreach and Iterator traversal.

Vector: is a thread-safe dynamic array. At the bottom is the array structure, which is initialized to an array of length 10. If the capacity is full, it will be expanded by 2.0x. In addition to supporting foreach and Iterator traversal, Enumeration iteration is also supported.

LinkedList: it is a two-way linked list, and the underlying structure is a linked list. When frequently inserting and deleting elements in the collection, the efficiency is higher, but the efficiency of lookup traversal is low.

3. Map interface

Map collection: saves a pair of objects

Sets with mapping in the form of "Key-Value"

1. Key and value in Map can be data of any reference type.

2. The key in Map is stored in set, and repetition is not allowed, that is, the class corresponding to the same Map object needs to override the hashCode and equals methods.

3. There is an one-way one-to-one correspondence between key and value in Map. Through the specified key, the value of value can be determined uniquely.

How does Map maintain KMTV?

Entry: horizontally, there are key-value pairs in the entry object, and several Entry form a Map (unordered non-repeatable) EntrySet

From a vertical point of view, KeySet has a special key and Collection has a value.

> HashMap

HashMap is a thread-unsafe hash table, the underlying structure is JDK1.7 hour array + linked list, JDK1.8 time array + linked list / red-black tree.

The thread safety problem of HashMap can be solved by Collections's synchronizedMap (Map m) method.

> TreeMap

> Hashtable

Hashtable is a thread-safe hash table, and the underlying structure is array + linked list.

II. Scala set

> 1. There are three major categories of Scala collections: sequence Seq, set Set, and mapping Map. And all sets have their own expansive qualities.

> 2. For almost all collection classes, Scala provides both mutable and immutable versions under two packages

Immutable sets: scala.collection.immutable

An immutable set means that the object of the collection cannot be modified, and each time it is modified, a new object is generated. Here modification refers to a change, increase or decrease in length. It is possible to just modify the properties in the object.

Mutable set: scala.collection.immutable

A mutable set means that the original object can be modified without generating a new object.

Commonly used = >

1 、 Seq

Immutable: ~

-> IndexedSeq

Array,String-> underlying implicit conversion

-> LinearSeq

List,Queue,Stack

Variable: ~

ArrayBuffer

StringBuffer

2 、 Set

By default, Set uses immutable collections. If you want to use mutable collections, you need to import the package-scala.collection.mutable.Set

Unordered and non-repeatable data

3 、 Map

Creating a Map is immutable by default.

When using variable, it is the same as that of Java.

It is worth noting that:

According to key, there are two ways to get the value value ~

1. Get value

two。 Did not get it, return empty

Unlike java, Scala is not similar to the Java direct get (get ()) method. Scala adds a new type Option to avoid getting a null value.

There are two subclasses None under Option | Some-None equals no value, and Some will wrap the acquired value.

If None is returned, you can do secondary processing and give a default value.

If you really want to get Value through key, you can use the getOrElse (elem,default) function.

At this point, I believe you have a deeper understanding of "how Java and Scala collections are transformed into each other". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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