10 Java Tips – Series II

Java Tips

Java Tips – Series II

Въвеждане : 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. Надявам се, че това ще ви помогне да научите концепциите и да ги приложите в практически проекти,,en,Той също така ще ви помогне да се подготвите за интервюта, базирани на Java,,en,Наслади се на четенето,,en,Какво е колекцията рамка в Java,,en,Колекцията е група от обекти,,en,Пакетът java.util предоставя важни типове колекции,,en,Има два основни типа колекции, които са колекция и карта,,en,Типовете колекции съдържат група обекти,,en,като списъци и сетове,,en,Но типовете карти съдържат група обекти като ключови,,en,стойност двойки като HashMap и Hashtable,,en,Рамка за колекции,,en,е една от най-важните области в Java платформата,,en,Как да разширя масив след инициализация,,en,Следният пример показва как да разширим масив след инициализиране, като създадем нов масив,,en,Тук кодът основно добавя нови стойности към съществуващ масив,,en,Матрицата,,en. It will also help you to prepare for Java based interviews. Enjoy reading.







What is collections framework in java?

A: 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?

A: Following example shows how to extend an array after initialization by creating a new array. Here the code is basically appending the new values to an existing array. The arraycopy() методът трябва да се използва внимателно, в противен случай може да има проблем със загубата на данни в съществуващия масив,,en,имена = нов стринг,,en,х,,en,разширен = нов стринг,,en,продължен,,en,System.arraycopy,,en,names.length,,en,String str,,en,И резултатът ще бъде както следва,,en,Как да запълня,,en,инициализирайте веднага,,en,масив,,en,Този пример ще бъде попълнен,,en,инициализиране на всички елементи на масива в едно кратко,,en,масив с помощта на Array.fill,,en,ArrayName,,en,метод и Array.fill,,en,начален индекс,,en,завършващ индекс,,en,метод на Java Util клас,,en,публичен клас FillTest,,en,int array,,en,= new int,,en,Arrays.fill,,en,п = array.length,,en,Ако изпълните кода, резултатът ще бъде както следва,,en,Как да умножите две матрици с различни размери,,en,Следващият пример показва умножение на две правоъгълни матрици с помощта на два дефинирани от потребителя методи, умножени,,en,и mprint,,en,публична класа Матрица,,en,публичен статичен int,,en,умножавам,,en,m1,,hmn,m2,,en,int m1rows = m1.length,,en.

обществени клас Main {

публично статично невалидни основни(Низ[] опцията) {

Низ[] names = new String[] { “X”, “Y”, “Z” };

Низ[] extended = new String[5];

extended[3] = “D”;

extended[4] = “То”;

System.arraycopy(имена, 0, extended, 0, names.length);

за (String str : extended){

System.out.println(ул);

}

}

}

And the result will be as follows

X
Y
Z
D
То

How to fill (initialize at once) an array?

A: This example will fill (initialize all the elements of the array in one short) an array by using Array.fill (arrayname, стойност) method and Array.fill (arrayname, starting index, ending index, стойност) method of Java Util class.

import java.util.*;

public class FillTest {

публично статично невалидни основни(String опцията[]) {

int array[] = new int[6];

Arrays.fill(масив, 100);

за (int i=0, n=array.length; аз < N; I ) {

System.out.println(масив[аз]);

}

System.out.println();

Arrays.fill(масив, 3, 6, 50);

за (int i=0, n=array.length; аз< N; I ) {

System.out.println(масив[аз]);

}

}

}

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?

A: Following example shows multiplication of two rectangular matrices with the help of two user defined methods multiply ( Int [] [] ,Int [] []) and mprint(Int [] []).

public class Matrix{

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

int m1rows = m1.length;

int m1cols = m1,,en,дължина,,en,int m2rows = m2.length,,en,int m2cols = m2,,en,m1cols,,en,= m2rows,,en,хвърлят нов незаконно измама,,en,матрици,,en,не съвпадат,,en,m2rows,,en,резултат = нов int,,en,m1rows,,en,m2cols,,en,int j = 0,,en,int k = 0,,en,= m1,,hmn,връщане резултат,,en,Матричен печат,,en,публична статична празнота,,en,int редове = a.length,,en,int cols = a,,ca,редове ,,en,колони ,,en,редове,,en,argv,,en,int x,,en,int и,,es,int от,,pl,= Matrix.multiply,,en,Matrix.mprint,,en,Кодната проба ще доведе до следния резултат,,en,Как да обединим две масиви,,en,Този пример показва как да се слеят две масиви в един масив чрез използване на списък.Addall,,en,array1.asList,,en,array2,,en,метод на класа списък и Arrays.toString,,en,метод на клас Array,,en,Бъдете внимателни при задаването на един масив на друг,,en,Защото ако позоваванията на елементите на двете масиви тогава има шанс за каскаден ефект,,en,вмъкване на java.util.Arrays,,en,Структура a,,en,Структура б,,en,Най-,,pt,Най-,,bs,Списък на списъците = нов ArrayList,,en,Arrays.asList,,en[0].length;

int m2rows = m2.length;

int m2cols = m2[0].length;

ако (m1cols != m2rows){

throw new IllegalArgumentException(“matrices

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

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

за (int i=0; аз< m1rows; I ){

за (int j=0; J< m2cols; J ){

за (int k=0; к< m1cols; k ){

result[аз][J] += m1[аз][к] * m2[к][J];

return result;

)

}

}

}

}

/** Matrix print.

*/

public static void mprint(Int[][] на){

int rows = a.length;

int cols = a[0].length;

System.out.println(“масив[“+rows ”][“+cols ”] = {“);

за (int i=0; аз< rows; I ){

System.out.print(“{“);

за (int j=0; J< Графи; J ){

System.out.print(” ” + на[аз][J] + “,”);

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

}

}

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

}

публично статично невалидни основни(Низ[] 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

масив[2][3]={

{3, 2, 3}

{5, 9, 8}

};

масив[3][2]={

{4, 7}

{9, 3}

{8, 1}

};

масив[2][2]={

{63, 30}

{165, 70}

};







How to merge two arrays?

A: 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. Be careful when assigning one array to another. 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;

внос java.util.List;

обществени клас Main {

публично статично невалидни основни(String опцията[]) {

String a[] = { “A”, “То”, “I” };

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

List list = new ArrayList(Arrays.asList(на));

list.addAll,,en,c = list.toArray,,en,Arrays.toString,,en,Как да търсите минималния и максималния елемент в масив,,en,Този пример показва как да търсите минималния и максималния елемент в масив с помощта на Collection.max,,en,и Collection.min,,en,методи за събиране клас,,en,Въпреки че има други начини да се намерят и стойностите за макс и мин от масив, този API е най-ефективният за работа с масиви,,en,вмъкнете java.util.Collections,,en,числа =,,en,int min =,,ar,Collections.min,,en,численост,,en,int max =,,en,Collections.max,,en,Минимален брой,,en,мен,,ku,Макс. Номер,,en,макс,,en,Резултатът ще бъде както следва,,en,Как да направите обръщане на арилий,,en,Колективният API има метод, наречен обратно,,en,ArrayList,,en,Така че това се използва за обръщане на списък с масиви,,en,Следният пример ще ви покаже как да използвате приложния програмен интерфейс (API), за да накарате кода да работи,,en,ArrayList arrayList = нов ArrayList,,en,arrayList.add,,en(Arrays.asList(б));

обект[] c = list.toArray();

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

}

}

The code sample will produce the following result

[A, То, I, O, U]

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

A: 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;

обществени клас Main {

публично статично невалидни основни(Низ[] опцията) {

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?

A: Collections API has a method called reverse (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;

обществени клас Main {

публично статично невалидни основни(Низ[] опцията) {

ArrayList arrayList = new ArrayList();

arrayList.add(“A”);

arrayList.add(“B”);

arrayList.add(“C”);

arrayList.add(“D”);

arrayList.add(“То”);

System.out.println(“Преди обратната поръчка,,en,ArrayList,,en,Collections.reverse,,en,След обратната поръчка,,en,Резултатът от горния пример ще бъде както следва,,en,Как да сортирате масив и да вмъкнете елемент в него,,en,Следният пример показва как да се използва сортирането,,en,метод и метод, дефиниран от потребителя insertElement,,en,да изпълни задачата,,en,Сортът,,en,методът се използва за сортиране на масива от отрицателна към положителна стойност, след това персонализираната insertElement,,en,метод се използва за добавяне на допълнителни елементи в него,,en,публична класа MainClass,,en,Arrays.sort,,en,printArray,,en,Сортиран масив,,en,индекс индекс = Arrays.binarySearch,,en,Не намери,,en,@,,en,int newIndex = -index,,en,масив = insertElement,,en,newIndex,,en,с,,en,частна статична невалидна printArray,,en,array.length,,en,private static int,,en,insertElement,,en,int оригинал,,en,int елемент,,en,int индекс,,en,int length = original.length,,en,int дестинация,,en,оригинал,,en,= елемент,,en,за връщане,,en: ” + arrayList);

Collections.reverse(arrayList);

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

}

}

The result of the above example would be as follows.

Преди обратната поръчка,,en,ArrayList,,en,Collections.reverse,,en,След обратната поръчка,,en,Резултатът от горния пример ще бъде както следва,,en,Как да сортирате масив и да вмъкнете елемент в него,,en,Следният пример показва как да се използва сортирането,,en,метод и метод, дефиниран от потребителя insertElement,,en,да изпълни задачата,,en,Сортът,,en,методът се използва за сортиране на масива от отрицателна към положителна стойност, след това персонализираната insertElement,,en,метод се използва за добавяне на допълнителни елементи в него,,en,публична класа MainClass,,en,Arrays.sort,,en,printArray,,en,Сортиран масив,,en,индекс индекс = Arrays.binarySearch,,en,Не намери,,en,@,,en,int newIndex = -index,,en,масив = insertElement,,en,newIndex,,en,с,,en,частна статична невалидна printArray,,en,array.length,,en,private static int,,en,insertElement,,en,int оригинал,,en,int елемент,,en,int индекс,,en,int length = original.length,,en,int дестинация,,en,оригинал,,en,= елемент,,en,за връщане,,en: [A, B, C, D, То]

After Reverse Order: [То, D, C, B, A]







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

A: 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 {

публично статично невалидни основни(String опцията[]) хвърля Exception {

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

Arrays.sort(масив);

printArray(“Sorted array”, масив);

int index = Arrays.binarySearch(масив, 1);

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

+ index);

int newIndex = -index – 1;

array = insertElement(масив, 1, newIndex);

printArray(“With 1 added”, масив);

}

private static void printArray(String съобщение, int array[]) {

System.out.println(message

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

за (Int I = 0; аз < array.length; I ) {

ако (аз != 0){

System.out.print(“, “);

}

System.out.print(масив[аз]);

}

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;

}

}

Как да сортирате масив и да търсите елемент в него,,en,и binarySearch,,en,метод за изпълнение на задачата,,en,Потребителският метод printArray,,en,се използва за показване на изхода,,en,mport java.util.Arrays,,en,Ако изпълните кода, тогава приложението ще покаже резултата, както е показано по-долу,,en,Как да създадете банер с помощта на Applet,,en,Следният пример използва класа Thread и Graphics класа, за да покаже банера,,en,Функционалността на нишката е да даде ефект на анимация на банера,,en,За да видите изхода, аплета трябва да се изпълнява В браузър, който поддържа аплета,,en,публичният клас SampleBanner разширява приложението,,en,изпълнява Runnable,,en,String str =,,en,Това е прост банер,,en,булев б,,en,Color.gray,,en,setForeground,,en,b = невярно,,en,char ch,,en,ch = str.charAt,,en,str = str.substring,,en,str.length,,en,str = p,,ro,гл,,en,g.setColor,,en,g.fillRect,,en,Може да ви заинтересува,,en?

A: 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 {

публично статично невалидни основни(String опцията[]) хвърля Exception {

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

Arrays.sort(масив);

printArray(“Sorted array”, масив);

int index = Arrays.binarySearch(масив, 2);

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

}

private static void printArray(String съобщение, int array[]) {

System.out.println(message

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

за (Int I = 0; аз < array.length; I ) {

ако(аз != 0){

System.out.print(“, “);

}

System.out.print(масив[аз]);

}

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?

A: 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.

внос java.awt. *;

import java.applet.*;

public class SampleBanner extends Applet

implements Runnable{

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;

за( ; ; ) {

опитвам {

repaint();

Thread.sleep(250);

ch = str.charAt(0);

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

str = str + ch;

}

улов(InterruptedException д) {}

}

}

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(ул, 1, 150);

}

}








You may be interested in Java Съвети Серия I,,en,techalpine.com/10-java-tips-series-ii/,,en,techalpine.com/wp-content/uploads/2018/07/Java-Tips.png,,en also. Enjoy reading.

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share