搜索词>>java基础 耗时0.0720
  • java编程基础数组ArrayList使用详解

    java编程基础数组ArrayList使用详解<p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">Java编程基础中的ArrayList用于存储动态大小的元素集合。与大小固定的数组相反,ArrayList会在添加新元素时自动增大其大小。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">ArrayList是Java集合框架的一部分,它实现了Java的<code>List</code>接口。<img alt="list" class="img-thumbnail" src="/assist/images/blog/3a58de20c693483dba6ea4d6a42b7e2a.jpg" /></span></span></span><br /> <br />  </p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以下几点需要注意Java中的ArrayList -</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li> <p style="margin-left:0px; margin-right:0px">ArrayList是一个可调整大小的数组,也称为动态数组。它的尺寸越来越大,以适应新的元素,并在元素被移除时缩小尺寸。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">ArrayList内部使用数组来存储元素。就像数组一样,它允许您通过索引来检索元素。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">Java ArrayList允许重复值和空值。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">Java ArrayList是一个有序的集合。它维护元素的插入顺序。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">您不能创建原始类型,如一个ArrayList <code>int</code>,<code>chat</code>等你需要用盒装的类型,如<code>Integer</code>,<code>Character</code>,<code>Boolean</code>等。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">Java ArrayList不同步。如果多个线程同时尝试修改ArrayList,那么最终结果将是非确定性的。如果多个线程要修改它,你必须显式同步对ArrayList的访问。</p> </li> </ul> <h2 style="margin-left:0px; margin-right:0px; text-align:start">创建一个ArrayList并添加新的元素</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">这个例子显示:</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li>如何使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>ArrayList()</code></a>构造函数创建ArrayList 。</li> <li>使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#add-E-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>add()</code></a>方法向ArrayList添加新元素。</li> </ul> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; public class CreateArrayListExample { public static void main(String[] args) { // Creating an ArrayList of String List<String> animals = new ArrayList<>(); // Adding new elements to the ArrayList animals.add("Lion"); animals.add("Tiger"); animals.add("Cat"); animals.add("Dog"); System.out.println(animals); // Adding an element at a particular index in an ArrayList animals.add(2, "Elephant"); System.out.println(animals); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><br /> <span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出</span></span></span></p> <pre> <code class="language-html">[Lion, Tiger, Cat, Dog] [Lion, Tiger, Elephant, Cat, Dog]</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">从另一个集合创建一个ArrayList</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">这个例子显示:</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li> <p style="margin-left:0px; margin-right:0px">如何使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>ArrayList(Collection c)</code></a>构造函数从另一个ArrayList创建一个ArrayList 。</p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#addAll-java.util.Collection-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>addAll()</code></a>方法将现有ArrayList中的所有元素添加到新的ArrayList中。</p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; public class CreateArrayListFromCollectionExample { public static void main(String[] args) { List<Integer> firstFivePrimeNumbers = new ArrayList<>(); firstFivePrimeNumbers.add(2); firstFivePrimeNumbers.add(3); firstFivePrimeNumbers.add(5); firstFivePrimeNumbers.add(7); firstFivePrimeNumbers.add(11); // Creating an ArrayList from another collection List<Integer> firstTenPrimeNumbers = new ArrayList<>(firstFivePrimeNumbers); List<Integer> nextFivePrimeNumbers = new ArrayList<>(); nextFivePrimeNumbers.add(13); nextFivePrimeNumbers.add(17); nextFivePrimeNumbers.add(19); nextFivePrimeNumbers.add(23); nextFivePrimeNumbers.add(29); // Adding an entire collection to an ArrayList firstTenPrimeNumbers.addAll(nextFivePrimeNumbers); System.out.println(firstTenPrimeNumbers); } }</code></pre> </li> </ul> <p style="margin-left:0px; margin-right:0px; text-align:start"><br /> <span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">访问ArrayList中的元素</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">这个例子显示:</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li>如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#isEmpty--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>isEmpty()</code></a>方法检查ArrayList是否为空。</li> <li>如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#size--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>size()</code></a>方法找到ArrayList的大小。</li> <li>如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#get-int-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>get()</code></a>方法访问ArrayList中特定索引处的元素。</li> <li>如何使用该<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#set-int-E-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>set()</code></a>方法修改ArrayList中特定索引处的元素。</li> </ul> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; public class AccessElementsFromArrayListExample { public static void main(String[] args) { List<String> topCompanies = new ArrayList<>(); // Check is an ArrayList is empty System.out.println("Is the topCompanies list empty? : " + topCompanies.isEmpty()); topCompanies.add("Google"); topCompanies.add("Apple"); topCompanies.add("Microsoft"); topCompanies.add("Amazon"); topCompanies.add("Facebook"); // Find the size of an ArrayList System.out.println("Here are the top " + topCompanies.size() + " companies in the world"); System.out.println(topCompanies); // Retrieve the element at a given index String bestCompany = topCompanies.get(0); String secondBestCompany = topCompanies.get(1); String lastCompany = topCompanies.get(topCompanies.size() - 1); System.out.println("Best Company: " + bestCompany); System.out.println("Second Best Company: " + secondBestCompany); System.out.println("Last Company in the list: " + lastCompany); // Modify the element at a given index topCompanies.set(4, "Walmart"); System.out.println("Modified top companies list: " + topCompanies); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Is the topCompanies list empty? : true Here are the top 5 companies in the world [Google, Apple, Microsoft, Amazon, Facebook] Best Company: Google Second Best Company: Apple Last Company in the list: Facebook Modified top companies list: [Google, Apple, Microsoft, Amazon, Walmart]</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">从ArrayList中移除元素</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">这个例子显示:</span></span></span></p> <ol style="margin-left:30px; margin-right:0px"> <li> <p style="margin-left:0px; margin-right:0px">如何删除ArrayList |中给定索引处的元素 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">delete</a><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-int-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">(int索引)</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何从ArrayList |中删除元素 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">delete(Object o)</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何从给定集合中存在的ArrayList中移除所有元素| <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#remove-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">delete</a>All<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#removeAll-java.util.Collection-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">()</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何删除所有匹配给定谓词|的元素 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#removeIf-java.util.function.Predicate-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">removeIf()</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">如何清除ArrayList | <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#clear--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">clear()</a></p> </li> </ol> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class RemoveElementsFromArrayListExample { public static void main(String[] args) { List<String> programmingLanguages = new ArrayList<>(); programmingLanguages.add("C"); programmingLanguages.add("C++"); programmingLanguages.add("Java"); programmingLanguages.add("Kotlin"); programmingLanguages.add("Python"); programmingLanguages.add("Perl"); programmingLanguages.add("Ruby"); System.out.println("Initial List: " + programmingLanguages); // Remove the element at index `5` programmingLanguages.remove(5); System.out.println("After remove(5): " + programmingLanguages); // Remove the element "Kotlin" (The remove() method returns false if the element does not exist in the ArrayList) boolean isRemoved = programmingLanguages.remove("Kotlin"); System.out.println("After remove(\"Kotlin\"): " + programmingLanguages); // Remove all the elements belonging to the collection scriptingLanguages List<String> scriptingLanguages = new ArrayList<>(); scriptingLanguages.add("Python"); scriptingLanguages.add("Ruby"); scriptingLanguages.add("Perl"); programmingLanguages.removeAll(scriptingLanguages); System.out.println("After removeAll(scriptingLanguages): " + programmingLanguages); // Remove all the elements that satisfy the given predicate programmingLanguages.removeIf(new Predicate<String>() { @Override public boolean test(String s) { return s.startsWith("C"); } }); /* The above removeIf() call can also be written using lambda expression like this - programmingLanguages.removeIf(s -> s.startsWith("C")) */ System.out.println("After Removing all elements that start with \"C\": " + programmingLanguages); // Remove all elements from the ArrayList programmingLanguages.clear(); System.out.println("After clear(): " + programmingLanguages); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Initial List: [C, C++, Java, Kotlin, Python, Perl, Ruby] After remove(5): [C, C++, Java, Kotlin, Python, Ruby] After remove("Kotlin"): [C, C++, Java, Python, Ruby] After removeAll(scriptingLanguages): [C, C++, Java] After Removing all elements that start with "C": [Java] After clear(): []</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">迭代ArrayList</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以下示例显示如何使用迭代遍历ArrayList</span></span></span></p> <ol style="margin-left:30px; margin-right:0px"> <li>Java 8 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#forEach-java.util.function.Consumer-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>forEach</code></a>循环。</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#iterator--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>iterator()</code></a>。</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#iterator--" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>iterator()</code></a>和Java 8 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#forEachRemaining-java.util.function.Consumer-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">forEachRemaining()</a>方法。</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#listIterator-int-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>listIterator()</code></a>。</li> <li>每个循环都很简单。</li> <li>用索引循环。</li> </ol> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IterateOverArrayListExample { public static void main(String[] args) { List<String> tvShows = new ArrayList<>(); tvShows.add("Breaking Bad"); tvShows.add("Game Of Thrones"); tvShows.add("Friends"); tvShows.add("Prison break"); System.out.println("=== Iterate using Java 8 forEach loop ==="); tvShows.forEach(tvShow -> { System.out.println(tvShow); }); System.out.println("\n=== Iterate using an iterator() ==="); Iterator<String> tvShowIterator = tvShows.iterator(); while (tvShowIterator.hasNext()) { String tvShow = tvShowIterator.next(); System.out.println(tvShow); } System.out.println("\n=== Iterate using an iterator() and Java 8 forEachRemaining() method ==="); tvShowIterator = tvShows.iterator(); tvShowIterator.forEachRemaining(tvShow -> { System.out.println(tvShow); }); System.out.println("\n=== Iterate using a listIterator() to traverse in both directions ==="); // Here, we start from the end of the list and traverse backwards. ListIterator<String> tvShowListIterator = tvShows.listIterator(tvShows.size()); while (tvShowListIterator.hasPrevious()) { String tvShow = tvShowListIterator.previous(); System.out.println(tvShow); } System.out.println("\n=== Iterate using simple for-each loop ==="); for(String tvShow: tvShows) { System.out.println(tvShow); } System.out.println("\n=== Iterate using for loop with index ==="); for(int i = 0; i < tvShows.size(); i++) { System.out.println(tvShows.get(i)); } } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">=== Iterate using Java 8 forEach loop === Breaking Bad Game Of Thrones Friends Prison break === Iterate using an iterator() === Breaking Bad Game Of Thrones Friends Prison break === Iterate using an iterator() and Java 8 forEachRemaining() method === Breaking Bad Game Of Thrones Friends Prison break === Iterate using a listIterator() to traverse in both directions === Prison break Friends Game Of Thrones Breaking Bad === Iterate using simple for-each loop === Breaking Bad Game Of Thrones Friends Prison break === Iterate using for loop with index === Breaking Bad Game Of Thrones Friends Prison break</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">在遍历期间需要修改ArrayList时,<code>iterator()</code>和<code>listIterator()</code>方法很有用。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">考虑下面的例子,在<code>iterator.remove()</code>遍历它的时候我们使用方法从ArrayList中移除元素-</span></span></span></p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ArrayListIteratorRemoveExample { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(13); numbers.add(18); numbers.add(25); numbers.add(40); Iterator<Integer> numbersIterator = numbers.iterator(); while (numbersIterator.hasNext()) { Integer num = numbersIterator.next(); if(num % 2 != 0) { numbersIterator.remove(); } } System.out.println(numbers); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">[18, 40]</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">在ArrayList中搜索元素</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">下面的例子显示了如何:</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li> <p style="margin-left:0px; margin-right:0px">检查ArrayList是否包含给定的元素|  <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#contains-java.lang.Object-" rel="external nofollow" target="_blank">contains</a><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#contains-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">()</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">查找ArrayList |中第一次出现元素的索引 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#indexOf-java.lang.Object-" rel="external nofollow" target="_blank">indexOf</a><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#indexOf-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">()</a></p> </li> <li> <p style="margin-left:0px; margin-right:0px">查找ArrayList |中最后一次出现元素的索引 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#lastIndexOf-java.lang.Object-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank">lastIndexOf()</a></p> </li> </ul> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; public class SearchElementsInArrayListExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("John"); names.add("Alice"); names.add("Bob"); names.add("Steve"); names.add("John"); names.add("Steve"); names.add("Maria"); // Check if an ArrayList contains a given element System.out.println("Does names array contain \"Bob\"? : " + names.contains("Bob")); // Find the index of first occurrence of an element in an ArrayList System.out.println("indexOf \"Steve\": " + names.indexOf("Steve")); System.out.println("indexOf \"Mark\": " + names.indexOf("Mark")); // Find the index of the last occurrence of an element in an ArrayList System.out.println("lastIndexOf \"John\" : " + names.lastIndexOf("John")); System.out.println("lastIndexOf \"Bill\" : " + names.lastIndexOf("Bill")); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Does names array contain "Bob"? : true indexOf "Steve": 3 indexOf "Mark": -1 lastIndexOf "John" : 4 lastIndexOf "Bill" : -1</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">用户定义对象的ArrayList</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">由于ArrayList支持泛型,因此可以创建<strong>任何</strong>类型的ArrayList 。它可以是简单的类型,如<code>Integer</code>,<code>String</code>,<code>Double</code>或复杂类型等的ArrayLists的ArrayList,或包含HashMap的ArrayList或任何用户定义的对象的ArrayList。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">在以下示例中,您将学习如何创建用户定义对象的ArrayList。</span></span></span></p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class ArrayListUserDefinedObjectExample { public static void main(String[] args) { List<User> users = new ArrayList<>(); users.add(new User("Rajeev", 25)); users.add(new User("John", 34)); users.add(new User("Steve", 29)); users.forEach(user -> { System.out.println("Name : " + user.getName() + ", Age : " + user.getAge()); }); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Name : Rajeev, Age : 25 Name : John, Age : 34 Name : Steve, Age : 29</code></pre> <h2 style="margin-left:0px; margin-right:0px; text-align:start">排序ArrayList</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">对ArrayList进行排序是您在程序中遇到的一个非常常见的任务。在本节中,我会告诉你如何 -</span></span></span></p> <ul style="margin-left:30px; margin-right:0px"> <li>使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>Collections.sort()</code></a>方法对ArrayList进行排序。</li> <li>使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#sort-java.util.Comparator-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>ArrayList.sort()</code></a>方法对ArrayList进行排序。</li> <li>用自定义比较器对用户定义对象的ArrayList进行排序。</li> </ul> <h4 style="margin-left:0px; margin-right:0px; text-align:start">1.使用Collections.sort()方法对ArrayList进行排序</h4> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ArrayListCollectionsSortExample { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(13); numbers.add(7); numbers.add(18); numbers.add(5); numbers.add(2); System.out.println("Before : " + numbers); // Sorting an ArrayList using Collections.sort() method Collections.sort(numbers); System.out.println("After : " + numbers); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Before : [13, 7, 18, 5, 2] After : [2, 5, 7, 13, 18]</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start">2.使用ArrayList.sort()方法对ArrayList排序<br />  </p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class ArrayListSortExample { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Lisa"); names.add("Jennifer"); names.add("Mark"); names.add("David"); System.out.println("Names : " + names); // Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method. names.sort(new Comparator<String>() { @Override public int compare(String name1, String name2) { return name1.compareTo(name2); } }); // The above `sort()` method call can also be written simply using lambda expressions names.sort((name1, name2) -> name1.compareTo(name2)); // Following is an even more concise solution names.sort(Comparator.naturalOrder()); System.out.println("Sorted Names : " + names); } }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">输出:</span></span></span></p> <pre> <code class="language-html">Names : [Lisa, Jennifer, Mark, David] Sorted Names : [David, Jennifer, Lisa, Mark]</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start">3.使用自定义比较器对对象的ArrayList进行排序<br />  </p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Person { private String name; private Integer age; public Person(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "{" + "name='" + name + '\'' + ", age=" + age + '}'; } } public class ArrayListObjectSortExample { public static void main(String[] args) { List<Person> people = new ArrayList<>(); people.add(new Person("Sachin", 47)); people.add(new Person("Chris", 34)); people.add(new Person("Rajeev", 25)); people.add(new Person("David", 31)); System.out.println("Person List : " + people); // Sort People by their Age people.sort((person1, person2) -> { return person1.getAge() - person2.getAge(); }); // A more concise way of writing the above sorting function people.sort(Comparator.comparingInt(Person::getAge)); System.out.println("Sorted Person List by Age : " + people); // You can also sort using Collections.sort() method by passing the custom Comparator Collections.sort(people, Comparator.comparing(Person::getName)); System.out.println("Sorted Person List by Name : " + people); } }</code></pre> 输出: <pre> <code class="language-html">Person List : [{name='Sachin', age=47}, {name='Chris', age=34}, {name='Rajeev', age=25}, {name='David', age=31}] Sorted Person List by Age : [{name='Rajeev', age=25}, {name='David', age=31}, {name='Chris', age=34}, {name='Sachin', age=47}] Sorted Person List by Name : [{name='Chris', age=34}, {name='David', age=31}, {name='Rajeev', age=25}, {name='Sachin', age=47}]</code></pre>   <h2 style="margin-left:0px; margin-right:0px; text-align:start">同步对ArrayList的访问</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">ArrayList类不同步。如果多个线程同时尝试修改一个ArrayList,那么最终的结果变得不确定,因为一个线程可能会覆盖另一个线程所做的更改。</span></span></span></p> <h4 style="margin-left:0px; margin-right:0px; text-align:start">示例演示ArrayList在多线程环境中的不可预知行为</h4> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以下示例显示了当多个线程同时尝试修改ArrayList时发生的情况。</span></span></span></p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class UnsafeArrayListExample { public static void main(String[] args) throws InterruptedException { List<Integer> unsafeArrayList = new ArrayList<>(); unsafeArrayList.add(1); unsafeArrayList.add(2); unsafeArrayList.add(3); // Create a thread pool of size 10 ExecutorService executorService = Executors.newFixedThreadPool(10); // Create a Runnable task that increments the each element of the ArrayList by one Runnable task = () -> { incrementArrayList(unsafeArrayList); }; // Submit the task to the executor service 100 times. // All the tasks will modify the ArrayList concurrently for(int i = 0; i < 100; i++) { executorService.submit(task); } executorService.shutdown(); executorService.awaitTermination(60, TimeUnit.SECONDS); System.out.println(unsafeArrayList); } // Increment all the values in the ArrayList by one private static void incrementArrayList(List<Integer> unsafeArrayList) { for(int i = 0; i < unsafeArrayList.size(); i++) { Integer value = unsafeArrayList.get(i); unsafeArrayList.set(i, value + 1); } } }</code></pre> 上述程序的最终输出应该相等,<code>[101, 102, 103]</code>因为我们将ArrayList中的值增加了100次。但是如果你运行这个程序,它会在每次运行时产生不同的输出 -<br /> 输出: <pre> <code class="language-html">[96, 96, 98]</code></pre>   <h4 style="margin-left:0px; margin-right:0px; text-align:start">演示如何将并发修改同步到ArrayList的示例</h4> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">好吧!现在让我们看看我们如何<code>ArrayList</code>在多线程环境中同步访问。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以下示例显示了上一个示例的同步版本。与以前的程序不同,该程序的输出是确定性的,并且始终是相同的。</span></span></span></p> <pre> <code class="language-java">import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class SynchronizedArrayListExample { public static void main(String[] args) throws InterruptedException { List<Integer> safeArrayList = Collections.synchronizedList(new ArrayList<>()); safeArrayList.add(1); safeArrayList.add(2); safeArrayList.add(3); // Create a thread pool of size 10 ExecutorService executorService = Executors.newFixedThreadPool(10); // Create a Runnable task that increments the each element of the ArrayList by one Runnable task = () -> { incrementArrayList(safeArrayList); }; // Submit the task to the executor service 100 times. // All the tasks will modify the ArrayList concurrently for(int i = 0; i < 100; i++) { executorService.submit(task); } executorService.shutdown(); executorService.awaitTermination(60, TimeUnit.SECONDS); System.out.println(safeArrayList); } // Increment all the values in the ArrayList by one private static void incrementArrayList(List<Integer> safeArrayList) { synchronized (safeArrayList) { for (int i = 0; i < safeArrayList.size(); i++) { Integer value = safeArrayList.get(i); safeArrayList.set(i, value + 1); } } } }</code></pre> 输出: <pre> <code class="language-html">[101, 102, 103]</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">以上示例使用<a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedList-java.util.List-" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>Collections.synchronizedList()</code></a>方法来获取ArrayList的同步视图。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff">而且,对<code>incrementArrayList()</code>方法内的ArrayList的修改被封装在一个<code>synchronized</code>块中。这确保了两个线程不能同时增加ArrayList元素。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:rgba(0, 0, 0, 0.87)"><span style="font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif"><span style="background-color:#ffffff"><em><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html" rel="external nofollow" style="box-sizing:border-box; color:#419be8; text-decoration:none; word-wrap:break-word" target="_blank"><code>CopyOnWriteArrayList</code></a>如果你需要线程安全,你也可以使用。它是ArrayList类的线程安全版本。它通过创建ArrayList的新副本来实现所有的变异操作。</em></span></span></span></p>
  • Java如何复制目录_Java基础教程系列

    Java如何复制目录,Java基础教程系列,如果要将目录及其包含的所有子文件夹和文件从一个位置复制到另一个位置,请使用下面的代码,该代码使用递归遍历目录结构,然后使用Files.copy()函数复制文件Java如何复制目录,Java基础教程系列,如果要将目录及其包含的所有子文件夹和文件从一个位置复制到另一个位置,请使用下面的代码,该代码使用递归遍历目录结构,然后使用Files.copy()函数复制文件。文件夹复制实例 在此示例中,我将c:\temp下的所有子目录和文件复制到新位置c:\tempNew。import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class DirectoryCopyExample { public static void main(String[] args) throws IOException { //源目录 File sourceFolder = new File("c:\\temp"); //目标目录 File destinationFolder = new File("c:\\tempNew"); //调用复制 copyFolder(sourceFolder, destinationFolder); } /** * 此功能以递归方式将所有子文件夹和文件从sourceFolder复制到destinationFolder * */ private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException { //Check if sourceFolder is a directory or file //If sourceFolder is file; then copy the file directly to new location if (sourceFolder.isDirectory()) { //Verify if destinationFolder is already present; If not then create it if (!destinationFolder.exists()) { destinationFolder.mkdir(); System.out.println("Directory created :: " + destinationFolder); } //Get all files from source directory String files[] = sourceFolder.list(); //Iterate over all files and copy them to destinationFolder one by one for (String file : files) { File srcFile = new File(sourceFolder, file); File destFile = new File(destinationFolder, file); //递归调用复制子目录 copyFolder(srcFile, destFile); } } else { //使用文件复制工具进行复制 Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING); System.out.println("File copied :: " + destinationFolder); } } } 上方代码运行结果:Directory created :: c:\tempNew File copied :: c:\tempNew\testcopied.txt File copied :: c:\tempNew\testoriginal.txt File copied :: c:\tempNew\testOut.txt提示:使用Files.copy()方法,可以复制目录。 但是,目录内的文件不会被复制,因此即使原始目录包含文件,新目录也为空。同样,如果目标文件存在,则复制将失败,除非指定了REPLACE_EXISTING选项。
  • Java基础多线程之线程同步(主线程等待子线程结束)

    Java基础多线程之主线程等待子线程结束,Java基础编程之多线程入门学习篇。主要讲解几种方法来实现Java多线程中主线程等待子线程结束的最快方式。<h2>引言</h2>   随着互联网时代的发展。在Java编程中多线程来处理多任务降低任务响应时间已是一种趋势。这里主要讲解Java多线程入门的主线程等待子线程结束的几种方法。 <h2>一.通过线程的join()方法</h2> 通过join()方法来实现主线程等待子线程同步的例子如下<br /> 首先编写一个简单的测试用的线程类:<br />   <pre> <code class="language-java">package xqlee.net.project.demo.thread.waitchilds; public class ThreadChildOne extends Thread { public ThreadChildOne(String name) { super(name); } @Override public void run() { try { long time=1000 * ((int) (Math.random() * 10)); System.out.println("From Child:" + this.getName()+">>>Start["+time+"]"); sleep(time); System.out.println("From Child:" + this.getName()+">>>End"); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> 这里通过继承Thread来编写的一个线程类。<br /> <br /> 编写一个测试类来实现: <pre> <code class="language-java">package xqlee.net.project.demo.thread.waitchilds; import java.util.ArrayList; import java.util.List; public class TestWaitChildsOne { public static void main(String[] args) { try { System.out.println("From Main Thread:==>Start"); System.out.println("From Main Thread:开始调用子线程----》"); long start = System.currentTimeMillis(); List<ThreadChildOne> list = new ArrayList<>(); for (int i = 0; i < 6; i++) { ThreadChildOne threadChild = new ThreadChildOne("Child-" + i); threadChild.start(); list.add(threadChild); } for (ThreadChildOne threadChild : list) { threadChild.join(); } System.out.println("From Main Thread:子线程调用结束,耗时:" + (System.currentTimeMillis() - start)); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <br /> 执行测试类,观察控制台如下图:<br /> <img alt="通过join()实现线程同步的运行结果" class="img-thumbnail" src="/assist/images/blog/2ee34862b6bd4cd9a836c745f47db767.png" /><br /> 从上图我们可以看到成功的实现了主线程等待子线程同步。观察这里比最大子线程耗时多了3毫秒,可能是因为CPU切换线程耗时属于正常现象。<br />   <h2>二.通过JDK自带的工具类CountDownLatch来实现多线程的线程同步</h2> 编写一个简单的测试线程类: <pre> <code class="language-java">package xqlee.net.project.demo.thread.waitchilds; import java.util.concurrent.CountDownLatch; public class ThreadChildTwo extends Thread { private CountDownLatch countDownLatch; public ThreadChildTwo(String name, CountDownLatch countDownLatch) { super(name); this.countDownLatch = countDownLatch; } @Override public void run() { try { long time = 1000 * ((int) (Math.random() * 10)); System.out.println("From Child:" + this.getName() + ">>>Start[" + time + "]"); sleep(time); System.out.println("From Child:" + this.getName() + ">>>End"); } catch (Exception e) { e.printStackTrace(); } finally { // 倒数器减1 countDownLatch.countDown(); } } } </code></pre> <br /> 测试类: <pre> <code class="language-java">package xqlee.net.project.demo.thread.waitchilds; import java.util.concurrent.CountDownLatch; public class TestWaitChildsTwo { public static void main(String[] args) { try {// 创建一个初始值为5的倒数计数器 CountDownLatch countDownLatch = new CountDownLatch(5); //这里的数字=线程数+1 System.out.println("From Main Thread:==>Start"); System.out.println("From Main Thread:开始调用子线程----》"); long start = System.currentTimeMillis(); for (int i = 0; i < 5; i++) { ThreadChildTwo threadChild = new ThreadChildTwo("Child-" + i,countDownLatch); threadChild.start(); } // 阻塞当前线程,直到倒数计数器倒数到0 countDownLatch.await(); System.out.println("From Main Thread:子线程调用结束,耗时:" + (System.currentTimeMillis() - start)); } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <br /> 运行结果:<br /> <img alt="测试运行结果" class="img-thumbnail" src="/assist/images/blog/f18eb90839e1406b9086737df0fd2b35.png" />
  • Java Bean 基础验证

    在这篇快速文章中,我们将介绍使用标准框架 - JSR 380(也称为Bean Validation 2.0)来验证Java bean的基础知识。当然,在大多数应用程序中验证用户输入是超常见的需求,而Java Bean验证框架已成为处理这种逻辑的事实上的标准。<h2 style="margin-left:0px; margin-right:0px; text-align:start"><strong>1.概述</strong></h2> <blockquote> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway">在这篇快速文章中,我们将<strong>介绍</strong>使用标准框架 - JSR 380(也称为<em>Bean Validation 2.0)</em><strong>来验证Java bean的基础知识</strong><em>。</em></span></span><br /> <span style="color:#535353"><span style="font-family:raleway">当然,在大多数应用程序中验证用户输入是超常见的需求,而Java Bean验证框架已成为处理这种逻辑的事实上的标准。</span></span></p> </blockquote> <h2 style="margin-left:0px; margin-right:0px; text-align:start"><strong>2. JSR 380</strong></h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">JSR 380是用于Bean验证,JavaEE的和的JavaSE的一部分,这确保了一个bean的属性符合特定条件,使用注释如Java API的说明书中<em>@NotNull</em>,<em>@Min</em>,和  <em>@Max</em>。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">该版本需要Java 8或更高版本,并利用Java 8中添加的新功能(例如类型注释),并支持新类型(如<em>Optional</em>和<em>LocalDate)</em>。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">有关规格的完整信息,请继续阅读<a href="https://jcp.org/en/jsr/detail?id=380" rel="external nofollow" style="box-sizing:border-box; color:#63b175; text-decoration:none" target="_blank">JSR 380</a>。</span></span></span><br />  </p> <h2 style="margin-left:0px; margin-right:0px; text-align:start"><strong>3.依赖性</strong></h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">我们将使用Maven示例来显示所需的依赖关系,但当然,可以使用各种方式添加这些jar。</span></span></span><br />  </p> <h3 style="margin-left:0px; margin-right:0px; text-align:start"><strong>3.1。验证API</strong></h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">根据JSR 380规范,<em>validation-api</em>依赖包含标准验证API:</span></span></span></p> <pre> <code class="language-xml"><dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.0.Final</version> </dependency></code></pre>   <h3 style="margin-left:0px; margin-right:0px; text-align:start"><strong>3.2。验证API参考实现</strong></h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff"><strong>Hibernate Validator是验证API的参考实现。</strong></span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">要使用它,我们必须添加以下依赖项:</span></span></span></p> <pre> <code class="language-xml"><dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.2.Final</version> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator-annotation-processor</artifactId> <version>6.0.2.Final</version> </dependency></code></pre> 这里的一个快速提示:<strong><em>hibernate-validator</em>完全独立于Hibernate的持久化方面功能模块,</strong>并且通过添加它作为依赖项,我们不会将这些持久性方面功能模块添加到项目中。<br />   <h3 style="margin-left:0px; margin-right:0px; text-align:start"><strong>3.3。表达式语言依赖关系</strong></h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">JSR 380提供了对变量插值的支持,允许违规消息中的表达式。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">要解析这些表达式,我们必须添加对表达式语言API和该API实现的依赖关系。GlassFish提供了参考实现:</span></span></span></p> <pre> <code class="language-xml"><dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.6</version> </dependency></code></pre> 如果未添加这些JAR,则会在运行时收到错误消息,如下所示: <blockquote> <p><em>HV000183: Unable to load ‘javax.el.ExpressionFactory’. Check that you have the EL dependencies on the classpath, or use ParameterMessageInterpolator instead</em></p> </blockquote> <h2 style="margin-left:0px; margin-right:0px; text-align:start"><strong>4.使用验证注解</strong></h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">我们将在这里使用一个<em>用户</em> bean作为主要的例子,并且为它添加​​一些简单的验证:</span></span></span></p> <pre> <code class="language-java">import javax.validation.constraints.AssertTrue; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.validation.constraints.Email; public class User { @NotNull(message = "Name cannot be null") private String name; @AssertTrue private boolean working; @Size(min = 10, max = 200, message = "About Me must be between 10 and 200 characters") private String aboutMe; @Min(value = 18, message = "Age should not be less than 18") @Max(value = 150, message = "Age should not be greater than 150") private int age; @Email(message = "Email should be valid") private String email; // standard setters and getters }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">示例中使用的所有注释都是标准的JSR注释:</span></span></span></p> <ul style="list-style-type:disc"> <li><strong><em>@NotNull</em></strong> - 验证注释的属性值不为 <em> null</em></li> <li><strong><em>@AssertTrue</em></strong> - 验证注释的属性值是否为 <em>真</em></li> <li><strong><em>@Size </em></strong> - 验证注释的属性值的大小在属性<em> min</em>和<em> max之间</em> ; 可以应用于 <em> String</em>, <em> Collection</em>, <em> Map</em>和数组属性</li> <li><strong><em>@Min </em></strong> -<em>  v</em>验证注释的属性的值不小于<em>值 </em>属性</li> <li><strong><em>@Max </em></strong> - 验证注释的属性的值不大于<em>值</em>属性</li> <li><em><strong>@电子邮件</strong></em> - 验证注释的属性是一个有效的电子邮件地址</li> </ul> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">一些注释接受附加属性,但是<em>消息</em>属性对所有属性都是通用的。这是当相应属性的值未通过验证时通常会显示的消息。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">JSR中可以找到的一些附加注释是:</span></span></span></p> <ul style="list-style-type:disc"> <li><em><strong>@NotEmpty</strong></em> - 验证该属性不为空或空; 可以应用于<em> String</em>,<em> Collection</em>,<em> Map</em>或<em> Array</em>值</li> <li><em><strong>@NotBlank</strong></em> - 只能应用于文本值并验证属性不为空或空白</li> <li><em><strong>@Positive</strong></em>和<em><strong> @PositiveOrZero</strong></em> - 适用于数值并验证它们是严格正数,还是正数,包括0</li> <li><em><strong>@Negative</strong></em>和<em><strong> @NegativeOrZero</strong></em> - 应用于数字值并验证它们是严格否定的,或者是否定的,包括0</li> <li><em><strong>@Past</strong></em>和<em><strong> @PastOrPresent</strong></em> - 验证日期值是过去还是过去,包括现在; 可以应用于日期类型,包括在Java 8中添加的日期类型</li> <li><em><strong>@Future</strong>和<strong>@FutureOrPresent</strong></em> - 验证日期值是未来还是未来,包括现在</li> </ul> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff"><strong>验证注释也可以应用于集合的元素</strong>:</span></span></span></p> <pre> <code class="language-java">List<@NotBlank String> preferences;</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">在这种情况下,任何添加到首选项列表的值都将被验证。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">规范<strong>还支持</strong> Java 8中<strong>的新的</strong><strong><em>可选</em></strong><strong>类型</strong>:</span></span></span></p> <pre> <code class="language-java">private LocalDate dateOfBirth; public Optional<@Past LocalDate> getDateOfBirth() { return Optional.of(dateOfBirth); }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">在这里,验证框架将自动解包<em>LocalDate </em>值并对其进行验证。</span></span></span></p> <h2 style="margin-left:0px; margin-right:0px; text-align:start"><strong>5.程序化验证</strong></h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">一些框架 - 比如Spring--通过使用注释可以简单地触发验证过程。这主要是因为我们不必与编程验证API进行交互。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">现在让我们开始手动路线并以编程方式设置:</span></span></span></p> <pre> <code class="language-java">ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator();</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">为了验证一个bean,我们必须首先有一个<em>Validator</em>对象,它是使用<em>ValidatorFactory</em>构造的  。</span></span></span></p> <h3 style="margin-left:0px; margin-right:0px; text-align:start"><strong>5.1。定义Bean</strong></h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">我们现在要设置这个无效的用户 - 具有空<em>名称</em>值:</span></span></span></p> <pre> <code class="language-java">User user = new User(); user.setWorking(true); user.setAboutMe("Its all about me!"); user.setAge(50);</code></pre> <h3 style="margin-left:0px; margin-right:0px; text-align:start"><strong>5.2。验证Bean</strong></h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">现在我们有了一个<em>Validator</em>,我们可以通过将它传递给<em>validate</em>方法来验证我们的bean 。任何违反<em>用户</em>对象中定义的约束条件  都将作为一个<em>Set</em>返回。</span></span></span></p> <pre> <code class="language-java">Set<ConstraintViolation<User>> violations = validator.validate(user);</code></pre> 通过遍历违规,我们可以通过使用<em>getMessage </em>方法来获取所有违规消息。 <pre> <code class="language-java">for (ConstraintViolation<User> violation : violations) { log.error(violation.getMessage()); }</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">在我们的示例(<em>ifNameIsNull_nameValidationFails</em>)中,该集合将包含一个  <em>ConstraintViolation</em>,其中消息“ <em>Name不能为null</em> ”。</span></span></span></p> <h2 style="margin-left:0px; margin-right:0px; text-align:start"><strong>六,总结</strong></h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">本教程重点介绍了通过标准Java验证API的简单传递,并说明了使用<em>javax.validation</em>注释和API 进行bean验证的基础知识。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="color:#535353"><span style="font-family:raleway"><span style="background-color:#ffffff">本文中的概念的实现可以在GitHub项目中找到。我们将在即将发布的文章中介绍JSR 380和Hibernate Validator的更多功能。</span></span></span></p> <br /> <br /> <br />  
  • Java基础JVM中堆和栈理解

    Java基础JVM中堆和栈理解,收集各大网站各大牛人的语录,在Java中,内存主要分为两种,一种是栈(stack)内存,另一种就是堆内存(heap)(某些情况下说的堆栈内存是指栈内存)。<h2>一.概述</h2> 在Java中,内存主要分为两种,一种是栈(<span style="color:#ff0000"><strong>stack</strong></span>)内存,另一种就是堆内存(<strong><span style="color:#ff0000">heap</span></strong>)(<span style="color:#ff0000">某些情况下说的堆栈内存是指<strong>栈内存</strong></span>)。 <h2>二.堆内存</h2> <h3>2.1什么是堆内存?</h3> 堆内存(<strong><span style="color:#ff0000">heap</span></strong>)是是Java内存中的一种,它的作用是用于存储Java中的对象和数组,当我们new一个对象或者创建一个数组的时候,就会在堆内存中开辟一段空间给它,用于存放。 <h3>2.2.堆内存的特点</h3> <ul> <li><span style="color:#3f3f3f"><span style="font-family:"microsoft yahei""><span style="background-color:#ffffff">堆其实可以类似的看做是管道,或者说是平时去排队买票的的情况差不多,所以堆内存的特点就是:</span></span></span><strong><span style="color:#ff0000">先进先出,后进后出</span></strong><span style="color:#3f3f3f"><span style="font-family:"microsoft yahei""><span style="background-color:#ffffff">,也就是你先排队,好,你先买票。</span></span></span></li> <li>堆的优势是可以动态地分配内存大小,生存期也不必事先告诉编译器,Java的垃圾收集器会自动收走这些不再使用的数据。但缺点是,由于要 在运行时动态分配内存,存取速度较慢。</li> </ul> <h2>三.栈内存</h2> <h3>3.1什么是栈内存</h3>   栈内存是Java的另一种内存,主要是用来执行程序用的,比如:基本类型的变量和对象的引用变量<br />   实际上是<span style="color:#ff0000">只有一个出入口的队列</span>,即后进先出(First In Last Out),先分配的内存必定后释放。一般由,由系统自动分配,存放存放函数的参数值,局部变量等,自动清除。 <br />   还有,堆是全局的,堆栈是每个函数进入的时候分一小块,函数返回的时候就释放了,静态和全局变量,new 得到的变量,都放在堆中,局部变量放在堆栈中,所以函数返回,局部变量就全没了。 <br />   其实在实际应用中,堆栈多用来存储方法的调用。而对则用于对象的存储。 <br />   JAVA中的基本类型,其实需要特殊对待。因为,在JAVA中,通过new创建的对象存储在“堆”中,所以用new 创建一个小的、简单的变量,如基本类型等,往往不是很有效。因此,在JAVA中,对于这些类型,采用了与C、C++相同的方法。也就是说,不用new 来创建,而是创建一个并非是“引用”的“自动”变量。这个变量拥有它的“值”,并置于堆栈中,因此更高效。 <h3>3.2栈内存的特点</h3> <ul> <li><span style="color:#3f3f3f"><span style="font-family:"microsoft yahei""><span style="background-color:#ffffff">栈内存就好像一个矿泉水瓶,像里面放入东西,那么先放入的沉入底部,所以它的特点是:</span></span></span><span style="color:#ff0000"><strong>先进后出,后进先出;</strong></span></li> <li>存取速度比堆要快,仅次于寄存器,栈数据可以共享,但缺点是,存在栈中的数据大小与生存期必须是确定的,缺乏灵活性;</li> <li>栈内存可以称为一级缓存,由垃圾回收器自动回收;</li> <li>栈数据可以共享;</li> </ul> <h2>四.区别</h2>   JVM是基于堆栈的虚拟机.JVM为每个新创建的线程都分配一个堆栈.也就是说,对于一个Java程序来说,它的运行就是通过对堆栈的操作来完成的。堆栈以帧为单位保存线程的状态。JVM对堆栈只进行两种操作:以帧为单位的压栈和出栈操作。<br /> <br /> <strong>相同点:</strong> <ul> <li>都是属于Java内存的一种 </li> <li>系统都会自动去回收它,但是对于堆内存一般开发人员会自动回收它</li> </ul> <strong>不同点:</strong> <ul> <li>堆内存用来存放由new创建的对象和数组。</li> <li>栈内存用来存放方法或者局部变量等 </li> <li>堆是先进先出,后进后出 </li> <li>栈是后进先出,先进后出</li> </ul> <h2>五.举个栗子说明</h2> <ul> <li> 比较类里面的数值是否相等时,用equals()方法;</li> <li> 当测试两个包装类的引用是否指向同一个对象时,用==</li> </ul> <pre> <code class="language-java">String str1 = "abc";  String str2 = "abc";  System.out.println(str1==str2); //true </code></pre> <pre> <code class="language-java">String str1 =new String ("abc"); String str2 =new String ("abc"); System.out.println(str1==str2); // false </code></pre> <pre> <code class="language-java">String s1 = "ja"; String s2 = "va"; String s3 = "java"; String s4 = s1 + s2; System.out.println(s3 == s4);//false System.out.println(s3.equals(s4));//true </code></pre> <br />  
  • java编程中float/double类型的正确比较方法

    java基础编程中float/double类型的正确比较方法    实际上,这不仅是Java特有的问题。 几乎所有的编程语言都可以观察到它。 在计算机内存中,使用IEEE 754标准格式存储浮动和双打。 实际的存储和转换如何工作,它超出了本文的范围。<br />   现在,只要理解在计算和转换过程中可以在这些数字中引入较小的舍入误差。 这就是为什么仅仅依靠等式运算符(==)来比较浮点数是不可取的原因。 <h2>1.简单的比较方式[不推荐]数据不准确</h2> 首先看看简单的比较,以便理解简单比较究竟有什么错误。 在给定的程序中,我使用两种方法创建相同的浮点数(即1.1):<br /> i)加1,11次。<br /> i)乘以.1至11。<br /> 从理论上讲,这两次行动都能产生数字1.1。 当我们比较两种方法的结果时,它应该匹配。<br />   <pre> <code class="language-java">private static void simpleFloatsComparison() { //Method 1 double f1 = .0; for (int i = 1; i <= 11; i++) { f1 += .1; } //Method 2 double f2 = .1 * 11; System.out.println("f1 = " + f1); System.out.println("f2 = " + f2); if (f1 == f2) System.out.println("f1 and f2 are equal\n"); else System.out.println("f1 and f2 are not equal\n"); } </code></pre> 输出: <pre> <code class="language-html">f1 = 1.0999999999999999 f2 = 1.1 f1 and f2 are not equal</code></pre> <blockquote> <p>观察这两个值。 f1计算为1.0999999999999999。 它正是内部导致四舍五入的问题。 这就是为什么不推荐简单方式浮点比较的原因。</p> </blockquote> <h2>2.基于阈值的比较[推荐]</h2> <pre> <code class="language-java">private static void thresholdBasedFloatsComparison() { final double THRESHOLD = .0001; //Method 1 double f1 = .0; for (int i = 1; i <= 11; i++) { f1 += .1; } //Method 2 double f2 = .1 * 11; System.out.println("f1 = " + f1); System.out.println("f2 = " + f2); if (Math.abs(f1 - f2) < THRESHOLD) System.out.println("f1 and f2 are equal using threshold\n"); else System.out.println("f1 and f2 are not equal using threshold\n"); }</code></pre> <br /> 输出值: <pre> <code class="language-html">f1 = 1.0999999999999999 f2 = 1.1 f1 and f2 are equal using threshold</code></pre> <h2>3.使用BigDecimal比较[推荐]</h2> 在BigDecimal类中,您可以指定要使用的舍入模式和精确精度。 使用精确的精度限制,舍入误差大多可以解决。<br /> <br /> 最好的部分是BigDecimal数字是不可变的,即如果您创建一个值为“1.23”的BigDecimal BD,该对象将保持为“1.23”并且永远不会被更改。 这个类提供了很多方法可以用来对它的值进行数字操作。<br /> <br /> 您可以使用它的.compareTo()方法与BigDecimal数字进行比较。 比较时忽略比例。 <pre> <code class="language-java">a.compareTo(b); // returns (-1 if a < b), (0 if a == b), (1 if a > b)</code></pre> <blockquote> <p>切勿使用.equals()方法比较BigDecimals。 那是因为这个等于函数会比较尺度。 如果比例不同,.equals()将返回false,即使它们是数学上相同的数字。</p> </blockquote> <br /> 我们举一个例子来理解这个比较。 <pre> <code class="language-java">private static void testBdEquality() { BigDecimal a = new BigDecimal("2.00"); BigDecimal b = new BigDecimal("2.0"); System.out.println(a.equals(b)); // false System.out.println(a.compareTo(b) == 0); // true }</code></pre> 现在我们来验证一下,我们使用BigDecimal类来解决原始问题。 <pre> <code class="language-java">private static void bigDecimalComparison() { //Method 1 BigDecimal f1 = new BigDecimal("0.0"); BigDecimal pointOne = new BigDecimal("0.1"); for (int i = 1; i <= 11; i++) { f1 = f1.add(pointOne); } //Method 2 BigDecimal f2 = new BigDecimal("0.1"); BigDecimal eleven = new BigDecimal("11"); f2 = f2.multiply(eleven); System.out.println("f1 = " + f1); System.out.println("f2 = " + f2); if (f1.compareTo(f2) == 0) System.out.println("f1 and f2 are equal using BigDecimal\n"); else System.out.println("f1 and f2 are not equal using BigDecimal\n"); }</code></pre> <br /> 输出: <pre> <code class="language-html">f1 = 1.1 f2 = 1.1 f1 and f2 are equal using BigDecimal</code></pre> <br /> <br /> <br /> <br />  
  • mysql存储过程基础实例

    mysql存储过程基础实例1.选择一个数据库创建表TEST_USER,并插入一些测试数据 <pre> <code class="language-sql">DROP TABLE IF EXISTS TEST_USER; CREATE TABLE TEST_USER( id int primary key not null, name varchar(255), age int, sex varchar(2) ); insert into TEST_USER (id,name,age,sex) values(1,"测试名称1",8,"男"); insert into TEST_USER (id,name,age,sex) values(2,"测试名称2",14,"男"); insert into TEST_USER (id,name,age,sex) values(3,"测试名称3",13,"男"); insert into TEST_USER (id,name,age,sex) values(4,"测试名称4",28,"男"); insert into TEST_USER (id,name,age,sex) values(5,"测试名称5",13,"男"); insert into TEST_USER (id,name,age,sex) values(6,"测试名称6",8,"男"); insert into TEST_USER (id,name,age,sex) values(7,"测试名称1",28,"男"); </code></pre> 执行结果:<br /> <img alt="执行结果,模拟数据" class="img-thumbnail" src="/assist/images/blog/4a3c2e50-49ff-4355-80db-81a7b423f800.jpg" style="height:204px; width:446px" /><br /> 2.创建一个最基础的存储过程 <pre> <code class="language-sql">CREATE PROCEDURE PBase() BEGIN SELECT * FROM TEST_USER; END</code></pre> 执行结果:<br /> <img alt="基础1" class="img-thumbnail" src="/assist/images/blog/abd128c7-c9b3-4719-b424-c47219324e86.jpg" style="height:267px; width:557px" /><br /> 执行基础的存储过程: <pre> <code class="language-sql">call PBase();</code></pre> <img alt="2" class="img-thumbnail" src="/assist/images/blog/6c093ce3-56cc-4434-bf08-5aa933bea79a.jpg" style="height:390px; width:797px" /><br /> 3.创建一个带输入参数的存储过程 <pre> <code class="language-sql">DROP PROCEDURE IF EXISTS P1; CREATE PROCEDURE P1(IN maxAge INT) BEGIN SELECT * FROM TEST_USER t WHERE t.age>maxAge; END</code></pre> <br /> 调用: <pre> <code class="language-sql">call P1(10);</code></pre> <img alt="执行结果" class="img-thumbnail" src="/assist/images/blog/798df4d0-c655-477f-8447-150fb5633ccd.jpg" style="height:592px; width:878px" /><br /> 4.创建一个带有输出参数的存储过程 <pre> <code class="language-sql">drop PROCEDURE if exists P2; create PROCEDURE P2(out total int) begin select count(id) into total from test_user; end;</code></pre> 调用: <pre> <code class="language-sql">call p2(@out); select @out</code></pre> <img alt="输出" class="img-thumbnail" src="/assist/images/blog/f38f2ff7-6d82-41c3-9d95-a930e15e77ad.jpg" style="height:609px; width:759px" /><br /> 5.创建一个带输入参数又带输出参数的存储过程 <pre> <code class="language-sql">DROP PROCEDURE IF EXISTS P3; CREATE PROCEDURE P3(IN maxAge INT,OUT total INT) BEGIN SELECT count(id) into total FROM TEST_USER t WHERE t.age>maxAge; END </code></pre> 执行:<br /> <img alt="3" class="img-thumbnail" src="/assist/images/blog/30fdf4b9-f85e-41fa-b510-3c62add76530.jpg" style="height:644px; width:916px" /><br /> 6.创建一个即是输入又是输出参数并且喊判断语句的存储过程 <pre> <code class="language-sql">DROP PROCEDURE IF EXISTS P4; CREATE PROCEDURE P4(INOUT param INT) BEGIN IF param = 10 THEN SELECT count(id) into param FROM TEST_USER t; ELSE SELECT count(id) into param FROM TEST_USER t WHERE t.age<param; END IF; END</code></pre> <br /> 执行1:参数10 <pre> <code class="language-sql">set @param=10; call P4(@param); select @param; </code></pre> <br /> <img alt="1111" class="img-thumbnail" src="/assist/images/blog/7b42c24d-0b73-4cff-a713-1b43a1a8975c.jpg" style="height:592px; width:864px" /><br /> 执行:参数9 <pre> <code class="language-sql">set @param=9; call P4(@param); select @param; </code></pre> <img alt="123" class="img-thumbnail" src="/assist/images/blog/6f5122e4-1853-4c75-a80d-7ec302e6baf5.jpg" style="height:584px; width:728px" />
  • Bootstrap Tab基础使用

    Bootstrap Tab基础使用,首先是引入必要的css和js,这里暂时忽略核心代码:<ul class="nav nav-tabs">l; <li class="active">l;Bootstrap Tab基础使用,首先是引入必要的css和js,这里暂时忽略核心代码:<ul class="nav nav-tabs"> <li class="active"> <a href="#clientLinkmanTabContent" data-toggle="tab"> 联系人 </a> </li> <li> <a href="#clientFollowTabContent" data-toggle="tab"> 跟进记录 </a> </li> <li> <a href="#clientOrderTabContent" data-toggle="tab"> 业务记录 </a> </li> </ul> <div class="tab-content"> <div class="tab-pane fade in active" id="clientLinkmanTabContent"> 1 </div> <div class="tab-pane fade" id="clientFollowTabContent"> 2 </div> <div class="tab-pane fade" id="clientOrderTabContent"> 3 </div> </div>效果图:​​ 图像 小部件
  • java基础ArrayList与LinkedList的区别以及使用场景

    本文组要摘录了网上各位大佬的总结。作为笔记搜录。尽量详细的讲解ArrayList与LinkedList的区别以及在何时选择那个用。<h2>一.ArrayList与LinkedList的区别</h2>  说法一: <ol> <li>因为Array是基于索引(index)的数据结构,它使用索引在数组中搜索和读取数据是很快的。Array获取数据的时间复杂度是O(1),但是要新增或者删除数据却是开销很大的,因为这需要重排数组中的所有数据。</li> <li>相对于ArrayList,LinkedList插入是更快的。因为LinkedList不像ArrayList一样,不需要改变数组的大小,也不需要在数组装满的时候要将所有的数据重新装入一个新的数组,这是ArrayList最坏的一种情况,时间复杂度是O(n),而LinkedList中插入或删除的时间复杂度仅为O(1)。ArrayList在插入或sh数据删除需要更新索引(除了插入数组的尾部)。</li> <li>LinkedList需要更多的内存,因为ArrayList的每个索引的位置是实际的数据,而LinkedList中的每个节点中存储的是实际的数据和前后节点的位置</li> </ol> 说法二: <ol> <li>ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。 </li> <li>对于随机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList要移动指针。 </li> <li>对于新增和删除操作add和remove,LinedList比较占优势,因为ArrayList要移动数据。 </li> </ol> 以上说法均为正确。 <h2>二.ArrayList与LinkedList的使用场景</h2> LinkedList: <ul> <li> 你的应用不会随机访问数据。因为如果你需要LinkedList中的第n个元素的时候,你需要从第一个元素顺序数到第n个数据,然后读取数据。</li> <li> 你的应用更多的插入和删除元素,更少的读取数据。因为插入和删除元素不涉及重排数据,所以它要比ArrayList要快。</li> </ul> ArrayList: <ul> <li>你的应用需要随机访问数据,基本不会在list中插入或者删除元素</li> </ul>
  • nginx 用户基础认证配置

    nginx 用户基础认证配置,nginx添加nginx 用户认证配置