Coding using array data structure (II)

Coding using array data structure (II)

Definition array

		Student students[]=new Student[3];
		students[0]=new Student("张三",10);
		students[1]=new Student("李四",11);
		students[2]=new Student("王五",12);

            for(Student s:students){
			System.out.println(s);
	     	}
String[] abc = new String[] { "abc", "acd", "add" };
String[] abd = new String[] {"acd", "cd", "de"};

Another way to define an array

int arr2[];
// 定义一个数组,并且静态初始化
int arr[]=new int[]{1,2,3};

The definition of dynamic array

	                Object[] pointX = null;
		        Object[] pointY = null;
			String sql1 = "select t.* from place t";
			List<IBean> points =query(sql1, covergeId);
			 pointX = new Object[points.size()];
			 pointY = new Object[points.size()];
			for(int j=0;j<points.size();j++){
			 pointX[j]=points.get(j).get("X");
			 pointY[j]=points.get(j).get("Y");
			}
String [] sqls = new String[sheet.getLastRowNum()];
condictionSql = "INSERT INTO "+templateTable+"("+paramkey.toString()+")  VALUES( "+paramval.toString()+")";
}
sqls[i-1] = condictionSql;

 

Array Methods

java string array is converted

Array to a string of characters by the following manner:

char[] data =  {'a', 'b', 'd'};

String s = new String(data);

1.1 for loop

StringBuffer sb = new StringBuffer();

for(int i = 0; i < str.length;i++){

  sb.append(str[i]);

}

String s = sb.toString();

1.2 interception string obtained by array split method

String[] split = joinId.split(",");
String str = "0,1,2,3,4,5";
String[] arr = str.split(","); // 用,分割
System.out.println(Arrays.toString(arr)); // [0, 1, 2, 3, 4, 5]
	@RequestMapping (value="/user/showUserList")
	public String showUserList(Model model,String ids){
		String[] idsArray = ids.split(",");
		if(ids!="") {
			StringBuffer str = new StringBuffer();
			for(int i=0;i<idsArray.length;i++) {
				User user = userService.getUser(idsArray[i]);
				if(null != user)
				{
					String name = user.getUserName();
					str.append(name+',');
				}
			}
			model.addAttribute("membersName", str);
		}
		if(ids=="") {
			model.addAttribute("membersName", "");
		}
		
		model.addAttribute("members", ids);
		return "select/user/showUserList";
	}

1.3 Use of the array into a string join method StringUtils

String[] arr = { "0", "1", "2", "3", "4", "5" };
//数组转字符串 org.apache.commons.lang3.StringUtils
String str3 = StringUtils.join(arr); // 数组转字符串,其实使用的也是遍历
System.out.println(str3); // 012345
String str4 = StringUtils.join(arr, ","); // 数组转字符串(逗号分隔)(推荐)
System.out.println(str4); // 0,1,2,3,4,5

String.Join () Method: String.join () is a new method JDK8 (package without lead) type array of strings is recommended, the character array to a spliced ​​spliced ​​together to form a new string.

	                String location = glEmerg.getLOCATION();
			String[] str = location.split(",");
			String Xstr = str[0];
			String Ystr = str[1];
			String[] arr=new String[]{Xstr,Ystr};
			
			String newLocation = String.join(",",arr);

 

Arrays Tools

Arrays.toString arrays and collections into a string

	public static void main(String[] args) {
		int arr[]={1,7,3,8,2};
		System.out.println(arr);
		System.out.println("以字符串形式输出数组:"+Arrays.toString(arr));
		Arrays.sort(arr); // 给数组排序
		System.out.println("排序后的数组:"+Arrays.toString(arr));
		System.out.println(Arrays.binarySearch(arr, 1));
		Arrays.fill(arr, 0); // 将指定内容填充到数组中
		System.out.println("填充数组后的字符串:"+Arrays.toString(arr));
		
	}

Use the toString method ArrayUtils

// 数组转字符串 org.apache.commons.lang3.ArrayUtils
String str2 = ArrayUtils.toString(arr, ","); // 数组转字符串(逗号分隔,首尾加大括号)
System.out.println(str2); // {0,1,2,3,4,5}

Arrays.asList array into a list

add the parameter is passed as the current Item List in a store, even if you pass a List will only increase in other current List an element
addAll is passed in a List, all the elements of this List is added to the current List, that is the number of elements in the current List will increase the size of the incoming List

List<String> members =  new ArrayList<String>(Arrays.asList(activity.getMembers().split(",")));
		members.addAll(orgUserIds);
		members = new ArrayList<>(new HashSet<>(joinMembers));
		if(CollectionUtils.isEmpty(members))
		{
			return "";
		}
		return String.join(",", members);

Iterate

//普通的数组遍历方式
		for(int i=0;i<arr.length;i++){
			System.out.println(arr[i]);
		}

//foreach方式
		for(int j:arr){
			System.out.println(j);
		}

                int arr[]=new int[3];
		arr[0]=1; // 给数组元素赋值
		arr[2]=6; 
		for(int i=0;i<arr.length;i++){
			System.out.println(arr[i]);
		}

Collection of traversal methods

String[] strings = {"A", "B", "C", "D"};  
Collection stringList = java.util.Arrays.asList(strings);  
/* 开始遍历 */  
for (Iterator itr = stringList.iterator(); itr.hasNext();) {  
Object str = itr.next();  
System.out.println(str);  
}  
/* 依次输出“A”、“B”、“C”、“D” */  

foreach way to get an array of

		String[] orgString = {"001001","001002","001003","001004","001005","001006"};
		List<PipeVO> rushCount = pipeMapper.showPipeList(vo);

		List<PipeVO> zeroString = new ArrayList<PipeVO>();
		for (String  code : orgString) {
			boolean hasCde = false;
         }

Other methods Arrays utility class

	public static void main(String[] args) {
		int arr[]={1,7,3,8,2};
		System.out.println(arr);
		System.out.println("以字符串形式输出数组:"+Arrays.toString(arr));
		Arrays.sort(arr); // 给数组排序
		System.out.println("排序后的数组:"+Arrays.toString(arr));
		System.out.println(Arrays.binarySearch(arr, 1));
		Arrays.fill(arr, 0); // 将指定内容填充到数组中
		System.out.println("填充数组后的字符串:"+Arrays.toString(arr));
		
	}

Two-dimensional array

/*int arr[][]=new int[][]{{1,2,3},{4,5,6},{7,8,9}};
		
		for(int i=0;i<arr.length;i++){
			for(int j=0;j<arr[i].length;j++){
				System.out.print(arr[i][j]+" ");
			}
			System.out.println();
		}*/
		
		int [][]arr=new int[3][3];
		arr[1][2]=3;
		for(int i=0;i<arr.length;i++){
			for(int j=0;j<arr[i].length;j++){
				System.out.print(arr[i][j]+" ");
			}
			System.out.println();
		}

 

java array contains a value judgment

1, java contains a special character string judging by container

 String str = "abc";
        boolean status = str.contains("a");
        if(status){
            System.out.println("包含");
        }else{
            System.out.println("不包含");
        }

It may be determined or set array contains the string

java array into the list method to determine whether the array contains an element

import org.apache.commons.lang.StringUtils; 
String[] roleIdsArr = memberRoleIds.split(","); 
Arrays.asList(roleIdsArr).contains("5afd389c10174e21af1680dd9f79f049");

Use Arrays class asList () method of the array into List () collection, reuse contains () method of determining whether there is a value in the array

​
import org.apache.commons.lang.StringUtils; 
String memberRoleIds = userRole.getRoleId();
 String[] roleIdsArr = memberRoleIds.split(","); 
boolean containRoleId = Arrays.asList(roleIdsArr).contains("5afd389c10174e21af1680dd9f79f049");
 if(!containRoleId) {
}

​
	 String memberRoleIds = userRole.getRoleId();
	 String[] roleIdsArr = memberRoleIds.split(","); 
         String[] newRoleIdsArr = new String[roleIdsArr.length+1];
	 String memRolds = "";
	 boolean containRoleId = Arrays.asList(roleIdsArr).contains("5afd389c10174e");
	 if(!containRoleId) {
	for(int mm=0;mm<=roleIdsArr.length-1;mm++) {
		newRoleIdsArr[mm] =roleIdsArr[mm];
		 }										
 newRoleIdsArr[roleIdsArr.length]="5afd389c10174e21af1680dd9f79f049";
 memRolds = StringUtils.join(newRoleIdsArr, ","); 
 String pointMemRolds = "'"+memRolds+"'";
 upRoleSql = "UPDATE CT_USER SET ROLE_ID="+pointMemRolds+ "where ID_NUMBER="+pointIdNum;
 jdbcTemplate.update(upRoleSql);
 }
	public Map<String, List<String>> showPipeList(PipeVO vo)
	{
		
		Map<String, List<String>> maps = new HashMap<String, List<String>>();
		List<String> yearCovlist = new ArrayList<String>();
		List<String> orglist = new ArrayList<String>();
		String[] orgString = {"001001","001002","001003","001004","001005","001006"};
		List<PipeVO> rushCount = pipeMapper.showPipeList(vo);
		for (PipeVO pipeVO : rushCount) {
			BigDecimal yearCov = new BigDecimal("0");
			String counts = pipeVO.getRunUser();
			String orgs = pipeVO.getDepOrder();
			if(!Arrays.asList(orgString).contains(orgs)) {
				continue;
			}
			String dayCov = pipeVO.getDayCovRate();
			String eventCauseName = compareDic(orgs);
		    if(""!=eventCauseName&&(!eventCauseName.equals(""))) {
		    	if(null!=counts&&null!=dayCov) {
		    		 if(counts.equals("0")) {
		    			 continue;
		    		 }
					 BigDecimal num1 = new BigDecimal(counts);
					 BigDecimal num2 = new BigDecimal(dayCov);
					 yearCov = num2.divide(num1,2, BigDecimal.ROUND_HALF_UP); 
				}
		    }
			yearCovlist.add(eventCauseName);
			orglist.add(yearCov.toString());
		}

		maps.put("yearCovlist", yearCovlist);
		maps.put("orglist", orglist);
		return maps;
	}

2, java the indexOf method to find the position of a word in a string, but it may be determined whether a string contains a character.

		String str="sasdwewuiundmxcss";
		System.out.println("d在字符串str中第一次出现的索引位置:"+str.indexOf('d'));
		System.out.println("d在字符串str中第一次出现的索引位置,从索引5位置开始:"+str.indexOf('d',4));
 String str1 = "abcdefg";
        int result1 = str1.indexOf("a");
        if(result1 != -1){
            System.out.println("字符串str中包含子串“a”"+result1);
        }else{
            System.out.println("字符串str中不包含子串“a”"+result1);
        }

Specific use:

Delete multiple data operations

js

	var ids = $("#id").val();
var url=Leopard.getContextPath() +"/deleteTczb1.act";
	var idstr = "";
	for(var i=0;i<ids.length;i++){
		idstr+=(","+ids[i])
	}
	var paramData={ids:idstr};
	getData(url,paramData);

java background

@RequestMapping("/deleteTczb")
	@ResponseBody
	public Boolean deleteCzb(HttpServletRequest request, HttpServletResponse response){
		String ids = request.getParameter("ids");
		String[] idArray = ids.replaceFirst(",", "").split(",");
		String sql = "delete from SY_TYZJKXCZB t where P_ID in(";
		for (String string : idArray) {
			sql+=(",?");
		}
		sql+=")";
		
		SqlUtil.getExecutor().execute(sql.replaceFirst(",", ""), idArray);
		return true;
	}

In many cases through java string concatenation to stringBuffer

StringBuffer sql = new StringBuffer("select ID from TB where ID in (");
			StringBuffer temp = new StringBuffer();
			for (String ID : Id.split(",")) {
				temp.append(",?");
			}  
			sql.append(temp.toString().replaceFirst(",", ""));
			sql.append(")");

 

Published 370 original articles · won praise 88 · views 290 000 +

Guess you like

Origin blog.csdn.net/qq_35029061/article/details/100117016