10 Java Tips – Series II

Java Tips

Mẹo Java,,id,Loạt I,,en – Series II

Giới thiệu : This is the 2nd part of Java tips series. We have tried to focus more on the hands-on coding part rather that the theoretical one. Hy vọng điều này sẽ giúp bạn tìm hiểu các khái niệm và thực hiện chúng trong các dự án thực tế,,en,Nó cũng sẽ giúp bạn chuẩn bị cho các cuộc phỏng vấn dựa trên Java,,en,Thích đọc sách,,en,Khung bộ sưu tập trong java là gì,,en,Bộ sưu tập là một nhóm đối tượng,,en,gói java.util cung cấp các loại bộ sưu tập quan trọng,,en,Có hai loại bộ sưu tập cơ bản mà chúng là Bộ sưu tập và Bản đồ,,en,Các loại bộ sưu tập chứa một nhóm đối tượng,,en,như Danh sách và Bộ,,en,Nhưng các loại Bản đồ chứa nhóm các đối tượng làm khóa,,en,các cặp giá trị như HashMap và Hashtable,,en,Khung bộ sưu tập,,en,là một trong những lĩnh vực quan trọng nhất trong nền tảng Java,,en,Cách mở rộng mảng sau khi khởi tạo,,en. It will also help you to prepare for Java based interviews. Enjoy reading.







What is collections framework in java?

Một: Collection is a group of objects. java.util package provides important types of collections. There are two fundamental types of collections they are Collection and Map. Collection types hold a group of objects, like Lists and Sets. But Map types hold group of objects as key, value pairs like HashMap and Hashtable. Collections framework is one of the most important area in Java platform.

How to extend an array after initialization?

Một: Ví dụ sau đây cho thấy cách mở rộng một mảng sau khi khởi tạo bằng cách tạo một mảng mới,,en,Ở đây mã về cơ bản gắn thêm các giá trị mới vào một mảng hiện có,,en,Các mảng,,en,phương pháp nên được sử dụng cẩn thận nếu không có thể có vấn đề mất dữ liệu trong mảng hiện có,,en,tên = Chuỗi mới,,en,X,,en,extended = new String,,en,mở rộng,,en,System.arraycopy,,en,names.length,,en,Chuỗi str,,en,Và kết quả sẽ như sau,,en,Cách điền,,en,khởi tạo cùng một lúc,,en,một mảng,,en,Ví dụ này sẽ điền,,en,khởi tạo tất cả các phần tử của mảng trong một đoạn ngắn,,en,một mảng bằng cách sử dụng Array.fill,,en,mảng tên,,en,phương thức và Array.fill,,en,chỉ số bắt đầu,,en,-chỉ số kết thúc,,en,phương thức Java Util class,,en,lớp công khai FillTest,,en,mảng int,,en,= new int,,en,Arrays.fill,,en,n = mảng.length,,en,Nếu bạn chạy mã thì kết quả sẽ như sau,,en,Cách nhân hai ma trận với các kích thước khác nhau,,en. Here the code is basically appending the new values to an existing array. The arraycopy() method should be used carefully otherwise there may a problem of data loss in the existing array.

public class Main {

public static void main(Chuỗi[] args) {

Chuỗi[] names = new String[] { “X”, “và”, “Z” };

Chuỗi[] extended = new String[5];

extended[3] = “D”;

extended[4] = “Nó”;

System.arraycopy(names, 0, extended, 0, names.length);

cho (String str : extended){

System.out.println(str);

}

}

}

And the result will be as follows

X

Z
D

How to fill (initialize at once) an array?

Một: This example will fill (initialize all the elements of the array in one short) an array by using Array.fill (arrayname, giá trị) method and Array.fill (arrayname, starting index, ending index, giá trị) method of Java Util class.

import java.util.*;

public class FillTest {

public static void main(String args[]) {

int array[] = new int[6];

Arrays.fill(array, 100);

cho (int i=0, n=array.length; tôi < n; i ) {

System.out.println(array[tôi]);

}

System.out.println();

Arrays.fill(array, 3, 6, 50);

cho (int i=0, n=array.length; tôi< n; i ) {

System.out.println(array[tôi]);

}

}

}

If you run the code then the result will be as follows.

100
100
100
100
100
100
100
100
100
50
50
50

How to multiply two matrices of different dimensions?

Một: Ví dụ sau đây cho thấy phép nhân của hai ma trận hình chữ nhật với sự trợ giúp của hai phương thức do người dùng định nghĩa nhân,,en,và mprint,,en,ma trận lớp công khai,,en,static tĩnh int,,en,nhân,,en,m1,,hmn,m2,,en,int m1rows = m1.length,,en,int m1cols = m1,,en,chiều dài,,en,int m2rows = m2.length,,en,int m2cols = m2,,en,m1cols,,en,= m2rows,,en,ném IllegalArgumentException mới,,en,ma trận,,en,không khớp,,en,m2rows,,en,result = new int,,en,m1rows,,en,m2cols,,en,int j = 0,,en,int k = 0,,en,= m1,,hmn,kết quả trả về,,en,In ma trận,,en,-mã in tĩnh công cộng,,en,int rows = a.length,,en,int cols = a,,ca,hàng ,,en,cols ,,en,hàng,,en,argv,,en,int x,,en,int và,,es,int từ,,pl,= Matrix.multiply,,en,Matrix.mprint,,en,Mẫu mã sẽ tạo ra kết quả sau,,en,Làm thế nào để hợp nhất hai mảng,,en,Ví dụ này cho thấy làm thế nào để hợp nhất hai mảng thành một mảng bằng cách sử dụng danh sách.,,en,array1.asList,,en,mảng2,,en,phương thức của lớp List và Arrays.toString,,en,phương thức của lớp Array,,en ( int [] [] ,int [] []) and mprint(int [] []).

public class Matrix{

public static int[][] multiply(int[][] m1, int[][] m2){

int m1rows = m1.length;

int m1cols = m1[0].length;

int m2rows = m2.length;

int m2cols = m2[0].length;

nếu (m1cols != m2rows){

throw new IllegalArgumentException(“matrices

don’t match: “+ m1cols + ” != ” + m2rows);

int[][] result = new int[m1rows][m2cols];

cho (int i=0; tôi< m1rows; i ){

cho (int j=0; j< m2cols; j ){

cho (int k=0; k< m1cols; k ){

result[tôi][j] += m1[tôi][k] * m2[k][j];

return result;

)

}

}

}

}

/** Matrix print.

*/

public static void mprint(int[][] một){

int rows = a.length;

int cols = a[0].length;

System.out.println(“array[“+rows ”][“+cols ”] = {“);

cho (int i=0; tôi< rows; i ){

System.out.print(“{“);

cho (int j=0; j< cols; j ){

System.out.print(” ” + một[tôi][j] + “,”);

System.out.println(“},”);

}

}

System.out.println(“:;”);

}

public static void main(Chuỗi[] argv){

int x[][] ={

{ 3, 2, 3 },

{ 5, 9, 8 },

};

int y[][] ={

{ 4, 7 },

{ 9, 3 },

{ 8, 1 },

};

int z[][] = Matrix.multiply(x, y);

Matrix.mprint(x);

Matrix.mprint(y);

Matrix.mprint(z);

}

}

The code sample will produce the following result

array[2][3]={

{3, 2, 3}

{5, 9, 8}

};

array[3][2]={

{4, 7}

{9, 3}

{8, 1}

};

array[2][2]={

{63, 30}

{165, 70}

};







How to merge two arrays?

Một: This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class and Arrays.toString () method of Array class. Hãy cẩn thận khi gán một mảng cho mảng khác,,en,Bởi vì nếu tham chiếu của các phần tử của cả hai mảng thì có khả năng tác dụng xếp tầng,,en,nhập khẩu java.util.Arrays,,en,Chuỗi a,,en,Chuỗi b,,en,O,,pt,U,,bs,Danh sách danh sách = new ArrayList,,en,Arrays.asList,,en,list.addAll,,en,c = list.toArray,,en,Arrays.toString,,en,Cách tìm kiếm tối thiểu và phần tử tối đa trong một mảng,,en,Ví dụ này cho thấy cách tìm kiếm phần tử tối thiểu và tối đa trong một mảng bằng cách sử dụng Collection.max,,en,và Collection.min,,en,phương thức của lớp Collection,,en,Mặc dù có một số cách khác cũng để tìm các giá trị tối đa và min từ một mảng nhưng API này là một cách hiệu quả nhất để làm việc với các mảng,,en,nhập khẩu java.util.Collections,,en,số =,,en,int min =,,ar,Collections.min,,en,số,,en,int max =,,en,Bộ sưu tập.max,,en,Số lượng tối thiểu,,en,tôi,,ku,Số lượng tối đa,,en,tối đa,,en,Kết quả sẽ như sau,,en,Cách đảo ngược danh sách theo dõi,,en. Because if the references of the elements of both the arrays then there is chance of cascading effect.

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class Main {

public static void main(String args[]) {

String a[] = { “Một”, “Nó”, “I” };

String b[] = { “O”, “U” };

List list = new ArrayList(Arrays.asList(một));

list.addAll(Arrays.asList(b));

Object[] c = list.toArray();

System.out.println(Arrays.toString(c));

}

}

The code sample will produce the following result

[Một, Nó, I, O, U]

How to search the minimum and the maximum element in an array?

Một: This example shows how to search the minimum and maximum element in an array by using Collection.max () and Collection.min() methods of Collection class. Although there are some other ways also to find the max and min values from an array but this API is the most efficient one to work with arrays.

import java.util.Arrays;

import java.util.Collections;

public class Main {

public static void main(Chuỗi[] args) {

Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};

int min = (int) Collections.min(Arrays.asList(numbers));

int max = (int) Collections.max(Arrays.asList(numbers));

System.out.println(“Min number: ” + min);

System.out.println(“Max number: ” + max);

}

}

The result will be as follows

Min number: 1

Max number: 9

How to reverse an arraylist?

Một: API bộ sưu tập có phương thức được gọi ngược lại,,en,Lập danh sách,,en,Vì vậy, điều này được sử dụng để đảo ngược một danh sách mảng,,en,Ví dụ sau sẽ cho bạn thấy cách sử dụng API để làm cho mã hoạt động,,en,ArrayList arrayList = new ArrayList,,en,arrayList.add,,en,Trước khi đặt hàng ngược lại,,en,lập danh sách,,en,Collections.reverse,,en,Sau khi đặt hàng ngược lại,,en,Kết quả của ví dụ trên sẽ như sau,,en,Làm thế nào để sắp xếp một mảng và chèn một phần tử bên trong nó,,en,Ví dụ sau cho thấy cách sử dụng sắp xếp,,en,phương thức và phương thức do người dùng định nghĩa insertElement,,en,để hoàn thành nhiệm vụ,,en,Sắp xếp,,en,phương thức được sử dụng để sắp xếp mảng từ giá trị âm sang giá trị dương, sau đó là insertElement tùy chỉnh,,en,phương pháp được sử dụng để thêm các yếu tố bổ sung vào nó,,en,lớp công khai MainClass,,en,Arrays.sort,,en,printArray,,en,Mảng được sắp xếp,,en,int index = Arrays.binarySearch,,en,Không tìm thấy,,en,@,,en,int newIndex = -index,,en,array = insertElement,,en (ArrayList). So this is used to reverse an array list. The following example will show you how to use the API to make the code work.

import java.util.ArrayList;

import java.util.Collections;

public class Main {

public static void main(Chuỗi[] args) {

ArrayList arrayList = new ArrayList();

arrayList.add(“Một”);

arrayList.add(“B”);

arrayList.add(“C”);

arrayList.add(“D”);

arrayList.add(“Nó”);

System.out.println(“Before Reverse Order: ” + arrayList);

Collections.reverse(arrayList);

System.out.println(“After Reverse Order: ” + arrayList);

}

}

The result of the above example would be as follows.

Before Reverse Order: [Một, B, C, D, Nó]

After Reverse Order: [Nó, D, C, B, Một]







How to sort an array and insert an element inside it?

Một: The following example shows how to use sort () method and user defined method insertElement () to accomplish the task. The sort () method is used to sort the array from negative to positive value then the customized insertElement () method is used to add additional elements into it.

import java.util.Arrays;

public class MainClass {

public static void main(String args[]) throws Exception {

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray(“Sorted array”, array);

int index = Arrays.binarySearch(array, 1);

System.out.println(“Didn’t find 1 @ ”

+ index);

int newIndex = -index – 1;

array = insertElement(array, 1, newIndex,,en,Với,,en,private static void printArray,,en,mảng.length,,en,static tĩnh int,,en,insertElement,,en,int gốc,,en,phần tử int,,en,int index,,en,int length = original.length,,en,int đích,,en,nguyên,,en,= yếu tố,,en,trở về đích,,en,Làm thế nào để sắp xếp một mảng và tìm kiếm một phần tử bên trong nó,,en,và binarySearch,,en,phương pháp để hoàn thành nhiệm vụ,,en,Phương thức do người dùng định nghĩa printArray,,en,được sử dụng để hiển thị đầu ra,,en,mport java.util.Arrays,,en,Nếu bạn chạy mã thì ứng dụng sẽ hiển thị kết quả như được đưa ra bên dưới,,en,Cách tạo banner bằng Applet,,en,Ví dụ sau đã sử dụng lớp Thread và Graphics class để hiển thị banner,,en,Chức năng của chủ đề là tạo hiệu ứng hoạt ảnh cho biểu ngữ,,en,Để xem đầu ra, applet sẽ được chạy Trong một trình duyệt hỗ trợ applet,,en,nhập java.applet. *,,en,lớp công khai SampleBanner mở rộng Applet,,en);

printArray(“With 1 added”, array);

}

private static void printArray(String tin nhắn, int array[]) {

System.out.println(lời nhắn

+ “: [length: ” + array.length + “]”);

cho (int i = 0; tôi < array.length; i ) {

nếu (tôi != 0){

System.out.print(“, “);

}

System.out.print(array[tôi]);

}

System.out.println();

}

private static int[] insertElement(int original[],

int element, int index) {

int length = original.length;

int destination[] = new int[length + 1];

System.arraycopy(original, 0, destination, 0, index);

destination[index] = element;

System.arraycopy(original, index, destination, index

+ 1, length – index);

return destination;

}

}

How to sort an array and search an element inside it?

Một: The following example shows how to use sort () and binarySearch () method to accomplish the task. The user defined method printArray () is used to display the output.

mport java.util.Arrays;

public class MainClass {

public static void main(String args[]) throws Exception {

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray(“Sorted array”, array);

int index = Arrays.binarySearch(array, 2);

System.out.println(“Found 2 @ ” + index);

}

private static void printArray(String tin nhắn, int array[]) {

System.out.println(lời nhắn

+ “: [length: ” + array.length + “]”);

cho (int i = 0; tôi < array.length; i ) {

nếu(tôi != 0){

System.out.print(“, “);

}

System.out.print(array[tôi]);

}

System.out.println();

}

}

If you run the code then the application will show the result as given below.

Sorted array: [length: 10]

-9, -7, -3, -2, 0, 2, 4, 5, 6, 8

Found 2 @ 5

How to create a banner using Applet?

Một: The following example has used the Thread class and Graphics class to display the banner. The functionality of the thread is to give an effect of animation to the banner. To view the output the applet should be run In a browser which supports applet.

import java.awt. *;

import java.applet.*;

public class SampleBanner extends Applet

triển khai Runnable,,en,Chuỗi str =,,en,Đây là một Banner đơn giản,,en,Chủ đề t,,en,boolean b,,en,public void init,,en,Màu xám,,en,setForeground,,en,Màu vàng,,en,công khai void bắt đầu,,en,t = chủ đề mới,,en,b = sai,,en,t.start,,en,công khai void chạy,,en,char ch,,en,Sơn lại,,en,ch = str.charAt,,en,str = str.substring,,en,str.length,,en,str = p,,ro,ch,,en,công cộng sơn rỗng,,en,Đồ họa g,,en,g.drawRect,,en,g.setColor,,en,g.fillRect,,en,Màu đỏ,,en,g.drawString,,en,Bạn có thể quan tâm,,en,Mẹo Java Series I,,en{

String str = “This is a simple Banner “;

Thread t ;

boolean b;

public void init() {

setBackground(Color.gray);

setForeground(Color.yellow);

}

public void start() {

t = new Thread(this);

b = false;

t.start();

}

public void run () {

char ch;

cho( ; ; ) {

thử {

repaint();

Thread.sleep(250);

ch = str.charAt(0);

str = str.substring(1, str.length());

str = str + ch;

}

bắt(InterruptedException e) {}

}

}

public void paint(Graphics g) {

g.drawRect(1,1,300,150);

g.setColor(Color.yellow);

g.fillRect(1,1,300,150);

g.setColor(Color.red);

g.drawString(str, 1, 150);

}

}








You may be interested in Java Tips Series I also. Enjoy reading.

============================================= ============================================== Mua sách Techalpine tốt nhất trên Amazon,en,Thợ điện CT Hạt dẻ,en
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Thưởng thức blog này,,en,làm ơn mở rộng vốn từ,,en,techalpine.com/apache-mahout-and-machine-learning,,en? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share